append和appendChild是两个经常使用的方法,用于将元素添加到文档对象模型(DOM)中。它们常常能够互换使用,没有太多麻烦,但若是它们是同样的,那么为何要出现两个API呢?……它们只是类似,但不是同样。javascript
此方法用于以Node对象或DOMString(基本上是文本)的形式添加元素。html
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>
复制代码
const parent = document.createElement('div');
parent.append('附加文本');
复制代码
而后 div
看起来像这样的java
<div>附加文本</ div>
复制代码
与 .append
方法相似,该方法用于DOM中的元素,但在这种状况下,只接受一个Node对象。app
const parent = document.createElement('div');
const child = document.createElement('p');
parent.appendChild(child);
复制代码
这会将子元素追加到 div
元素,而后 div
看起来像这样ui
<div> <p> </ p> </ div>
复制代码
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对象。spa
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
仅容许单个项目。code
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
,但反过来不行。cdn
来源:dev.to,做者:Abdulqudus Abubakre,翻译:公众号《前端全栈开发者》