在 JavaScript 中,append()
和 appendChild()
都可以用来向元素中添加子节点,但它们之间存在一些区别:
1.两者添加元素的位置不同:
appendChild():将新节点添加到其父节点的子节点列表的末尾。如果新节点已经是文档中的一个节点,那么它将从原来的位置被移除,然后添加到新位置的末尾。
const parentDiv = document.createElement('div');
const childDiv1 = document.createElement('div');
const childDiv2 = document.createElement('div');
parentDiv.appendChild(childDiv1);
parentDiv.appendChild(childDiv2);
append():可以将一个节点或字符串添加到其父节点的末尾。如果添加的是字符串,它会被当作文本节点添加。如果添加的是节点,其效果与 appendChild()
类似,将节点添加到末尾,如果节点已存在则先移除再添加。
const parentDiv = document.createElement('div');
const childDiv1 = document.createElement('div');
const childDiv2 = document.createElement('div');
parentDiv.append(childDiv1);
parentDiv.append(childDiv2);
parentDiv.append('Hello');
2. 参数类型
appendChild():只能接受一个节点作为参数,不能直接添加文本字符串。
append():可以接受一个节点或一个字符串作为参数,也可以接受多个参数,这些参数可以是节点或字符串的组合。
const parentDiv = document.createElement('div');
const childDiv1 = document.createElement('div');
const childDiv2 = document.createElement('div');
parentDiv.append(childDiv1, 'Hello', childDiv2);
3. 兼容性
appendChild():是一个历史悠久的方法,在所有主流浏览器中都得到了广泛支持,包括一些较老的浏览器版本。
append():是较新的方法,虽然在现代浏览器中得到了较好的支持,但在一些较老的浏览器版本中可能不兼容,如 IE 浏览器等。
4. 返回值
appendChild():返回被添加的节点。
const parentDiv = document.createElement('div');
const childDiv = document.createElement('div');
const appendedNode = parentDiv.appendChild(childDiv);
console.log(appendedNode === childDiv); // true
append():没有返回值。