首页 >  html代码 >  append和appendChild比较

append和appendChild比较

append和appendChild是两个常用的方法,用于将元素添加到文档对象模型(DOM)中。二者大部分情况下可以互换,但还是有几点区别:

一、append 接受Node对象和DOMString,而 appendChild 只接受Node对象。

const parent = document.createElement('div');

const child = document.createElement('p');

// 追加节点对象

parent.append(child); // ok

parent.appendChild(child) ;// ok

// 追加DOMStrings

parent.append('Hello world') // ok

parent.appendChild('Hello world') // 抛出错误,无法添加DOMString

二、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'); // ok

parent.appendChild(child, childTwo, 'Hello world');// 只添加第一个元素,而忽略其余元素

综上:基本上append适用性较广,当然只需要添加单个节点时候,appendClild更为契合