在 JavaScript 里,append
和 appendChild
都能够往一个父元素里添加子元素,不过它们存在一些显著差异。下面我们会详细探讨这些差异,并给出示例代码。
1. 参数类型
- appendChild:此方法仅接受一个
Node
类型的参数,也就是说,你只能传入一个 DOM 节点。 - append:这个方法可以接受
Node
类型的参数,也能接受字符串类型的参数。你既可以添加 DOM 节点,也能添加纯文本。
2. 返回值
- appendChild:会返回被添加的子节点。
- append:没有返回值(返回
undefined
)。
3. 一次添加多个元素
- appendChild:一次只能添加一个子节点。若要添加多个节点,就得多次调用该方法。
- append:能够一次添加多个节点或者字符串。
示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>append vs appendChild</title>
</head>
<body>
<div id="parent"></div>
<script>
// 获取父元素
const parent = document.getElementById('parent');
// 创建一个新的段落元素
const newParagraph = document.createElement('p');
newParagraph.textContent = 'This is a new paragraph.';
// 使用 appendChild 添加元素
const returnedNode = parent.appendChild(newParagraph);
console.log('appendChild 返回值:', returnedNode);
// 创建另一个新的段落元素
const anotherParagraph = document.createElement('p');
anotherParagraph.textContent = 'This is another paragraph.';
// 使用 append 添加元素和文本
parent.append(anotherParagraph, ' This is some text.');
console.log('append 返回值:', parent.append(anotherParagraph, ' This is some text.')); // 输出 undefined
</script>
</body>
</html>
代码解释:
- appendChild:
- 先创建一个新的
<p>
元素,接着使用appendChild
把它添加到父元素中。 appendChild
方法返回被添加的<p>
元素,这个返回值会被记录在returnedNode
变量里。
- 先创建一个新的
- append:
- 又创建了一个新的
<p>
元素。 - 运用
append
方法把这个新的<p>
元素和一段纯文本添加到父元素中。 append
方法没有返回值,所以console.log
输出undefined
。
- 又创建了一个新的
总结
- 要是你仅需添加单个 DOM 节点,并且需要获取被添加的节点,那么
appendChild
会是个不错的选择。 - 若你想一次性添加多个节点或者字符串,且不需要返回值,
append
会更合适。