例如,如果我有一个只是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元素
我们可以进行类似ParentNode.append()
的操作。通过使用可重用的Element构造函数,我非常喜欢这个概念:
myNav.append(EL_logo, EL_list, EL_btn)
/**
* Create new Element helper
* @param {String} tag Element TagName selector
* @param {Object} attr Element attributes
*/
const EL = (tag, attr = {}) => Object.assign(document.createElement(tag), attr);
和附加DocumentFragment
const EL = (tag, attr = {}) => Object.assign(document.createElement(tag), attr);
const EL_h1 = EL("h1", {
textContent: "Hello, World!"
});
const EL_btn = EL("button", {
textContent: "Click me!",
type: "button",
style: "color: blue;",
onclick() {
alert(this.textContent);
}
});
document.body.append(EL_h1, EL_btn);
const EL = (tag, attr = {}) => Object.assign(document.createElement(tag), attr);
const EL_a = EL("div", {
textContent: "Some DIV Lorem ipsum"
});
const EL_b = EL("div", {
innerHTML: "dolor <b>sit amet</b>"
});
const DF = new DocumentFragment();
DF.append(EL_a, EL_b); // Append to DocumentFragment first
// Here you can still manipulate DF using i.e: DF.querySelectorAll('div');
document.body.append(DF); // Append DocumentFragment
const EL = (tag, attr = {}) => Object.assign(document.createElement(tag), attr);
// Prepare UL Element
const EL_ul = EL('ul');
// Function for LI Element
const EL_Li = (textContent) => EL('li', {
textContent,
onclick( evt ) {
console.log(this.textContent);
}
});
const DF_list = new DocumentFragment();
const items = ["Click me!", "Lorem", "Ipsum", "Dolor"];
items.forEach(item => DF_list.append(EL_Li(item)));
EL_ul.append(DF_list);
// Finally append the UL element somewhere
document.body.append(EL_ul);