javascript - 如何使用 JavaScript 将元素附加到空 html 文件?

标签 javascript html css dom

例如,如果我有一个 html 文件,它就是

<html>


</html>

我有类似的东西

const div=document.createElement('div');

如何将 div 附加到空 html 文件? 我尝试过执行 document.appendChild(div),但这不起作用。

最佳答案

通过选择器查询获取Html元素并附加div

const div = document.createElement('div');    
const htmlElement = document.querySelector("html");    
htmlElement.appendChild(div)

或者只是:

const div = document.createElement('div');  
document.documentElement.appendChild(div);

document.documentElement 获取html元素

关于javascript - 如何使用 JavaScript 将元素附加到空 html 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61038003/

相关文章:

php - 在 php html javascript 中自定义 paypal 集成

javascript - node.js 表达 response.write() 在 Safari 中不是异步的

php - 如何将 mysql 中的行乘以表单中的数量?

html - 推特 Bootstrap 导航栏中的 Glyphicon 和 Select

html - 在 Firebug 中显示当前事件的媒体查询规则

javascript - 垂直对齐按钮在 Ionic 中没有滚动

javascript - 如何像梯形一样对齐文本?

javascript - 将不同的图像强制设置为相同的高度,以便组合宽度填充固定的 div

html - 在右对齐图标周围环绕文字?

html - Bootstrap 中心内容很好