簡體   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