繁体   English   中英

如何使用 javascript 将 append 元素添加到空的 html 文件?

[英]How do I append elements to an empty html file using javascript?

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

<html>


</html>

我有类似的东西

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

我将如何 append 将 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()

我们可以做类似的事情: myNav.append(EL_logo, EL_list, EL_btn)
通过使用可重用的 Element 构造函数,这是我非常喜欢的一个概念:

/**
 * 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);

Append 元素到 DOM

 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);

使用 DocumentFragment 进行分组

并附加 DocumentFragment

 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 ie: 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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM