附加 VS 附加子项
这是“这 vs 那”系列的第一篇文章。本系列旨在比较两个经常混淆的术语、方法、对象、定义或任何与前端相关的内容。
append 和 appendChild 是两种常用的向文档对象模型 (DOM) 添加元素的方法。它们经常互换使用,不会有什么问题,但如果它们相同,为什么不抄袭一个呢……其实它们只是相似,而不是完全不同。具体方法如下:
。附加()
此方法用于以 Node 对象或 DOMString(基本上是文本)的形式添加元素。其工作原理如下。
// Inserting a Node object
const parent = document.createElement('div');
const child = document.createElement('p');
parent.append(child);
// This appends the child element to the div element
// The div would then look like this <div><p></p></div>
// Inserting a DOMString
const parent = document.createElement('div');
parent.append('Appending Text');
// The div would then look like this <div>Appending Text</div>
.appendChild()
与.append方法类似,此方法用于 DOM 中的元素,但在这种情况下,只接受一个 Node 对象。
// Inserting a Node object
const parent = document.createElement('div');
const child = document.createElement('p');
parent.appendChild(child);
// This appends the child element to the div element
// The div would then look like this <div><p></p></div>
// Inserting a 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 对象和 DOMStrings,而.appendChild
仅接受 Node 对象const parent = document.createElement('div'); const child = document.createElement('p'); // Appending Node Objects parent.append(child) // Works fine parent.appendChild(child) // Works fine // Appending DOMStrings parent.append('Hello world') // Works fine parent.appendChild('Hello world') // Throws error
-
.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'); // Works fine parent.appendChild(child, childTwo, 'Hello world'); // Works fine, but adds the first element and ignores the rest
结论
在可以使用的情况下.appendChild
,可以使用,.append
但反之则不行。
目前就这些了,如果您需要我进一步解释任何术语,您可以在评论部分添加它们,也可以通过推特联系我
文章来源:https://dev.to/ibn_aubakre/append-vs-appendchild-a4m