append和appendChild是兩個常用的方法,用於將元素添加到文檔對象模型(DOM)中。它們經常可以互換使用,沒有太多麻煩,但如果它們是一樣的,那麼為什麼要出現兩個API呢?……它們只是相似,但不是一樣。

append()
此方法用於以Node對象或DOMString(基本上是文本)的形式添加元素。
插入一個Node對象
const parent = document.createElement('div');
const child = document.createElement('p');
parent.append(child);
// 這會將子元素追加到div元素
// 然後div看起來像這樣<div> <p> </ p> </ div>
這會將子元素追加到 div 元素,然後 div 看起來像這樣
<div> <p> </ p> </ div>
插入DOMString
const parent = document.createElement('div');
parent.append('附加文本');
然後 div 看起來像這樣的
<div>附加文本</ div>
appendChild()
與 .append 方法類似,該方法用於DOM中的元素,但在這種情況下,只接受一個Node對象。
插入一個Node對象
const parent = document.createElement('div');
const child = document.createElement('p');
parent.appendChild(child);
這會將子元素追加到 div 元素,然後 div 看起來像這樣
<div> <p> </ p> </ div>
插入DOMString
const parent = document.createElement('div');
parent.appendChild('Appending Text');
// Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'
不同點
.append 接受Node對象和DOMString,而 .appendChild 只接受Node對象。
const parent = document.createElement('div');
const child = document.createElement('p');
// 追加節點對象
parent.append(child) // 工作正常
parent.appendChild(child) // 工作正常
// 追加DOMStrings
parent.append('Hello world') // 工作正常
parent.appendChild('Hello world') // 拋出錯誤
.append 沒有返回值,而 .appendChild 返回附加的Node對象。
const parent = document.createElement('div');
const child = document.createElement('p');
const appendValue = parent.append(child);
console.log(appendValue) // undefined
const appendChildValue = parent.appendChild(child);
console.log(appendChildValue) // <p><p>
.append 允許您添加多個項目,而 .appendChild 僅允許單個項目。
const parent = document.createElement('div');
const child = document.createElement('p');
const childTwo = document.createElement('p');
parent.append(child, childTwo, 'Hello world'); // 工作正常
parent.appendChild(child, childTwo, 'Hello world');
// 工作正常,但添加第一個元素,而忽略其餘元素
總結
在可以使用 .appendChild 的情況下,可以使用 .append,但反過來不行。
如果對你有所啟發和幫助,可以點個關注、收藏、轉發,也可以留言討論,這是對作者的最大鼓勵。
作者簡介:Web前端工程師,全棧開發工程師、持續學習者。
原創文章,作者:投稿專員,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/273334.html