附加 VS 附加子项

2025-05-27

附加 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>
Enter fullscreen mode Exit fullscreen mode
// Inserting a DOMString
const parent = document.createElement('div');
parent.append('Appending Text');
// The div would then look like this <div>Appending Text</div>
Enter fullscreen mode Exit fullscreen mode

.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>
Enter fullscreen mode Exit fullscreen mode
// 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'
Enter fullscreen mode Exit fullscreen mode

差异

  1. .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
    
  2. .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>
    
  3. .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
PREV
用 10 行 JavaScript 实现视差效果
NEXT
React 教程:初学者综合指南(2023)