Understand that .children https://dom.spec.whatwg.org/#ref-for-dom-parentnode-children is a property of an Element https://dom.spec.whatwg.org/#interface-element. 1 Only Elements have .children
, and these children are all of type Element. 2
However, .childNodes https://dom.spec.whatwg.org/#ref-for-dom-node-childnodes is a property of Node https://dom.spec.whatwg.org/#interface-node. .childNodes
can contain any node. 3
一个具体的例子是:
let el = document.createElement("div");
el.textContent = "foo";
el.childNodes.length === 1; // Contains a Text node child.
el.children.length === 0; // No Element children.
大多数时候,您想要使用.children
因为通常你不想循环Text https://dom.spec.whatwg.org/#interface-text or Comment https://dom.spec.whatwg.org/#interface-commentDOM 操作中的节点。
If you do want to manipulate Text nodes, you probably want .textContent https://dom.spec.whatwg.org/#ref-for-dom-node-textcontent instead. 4
1. Technically, it is an attribute of ParentNode https://dom.spec.whatwg.org/#interface-parentnode, a mixin included by Element.
2. They are all elements because .children
is a HTMLCollection https://dom.spec.whatwg.org/#interface-htmlcollection, which can only contain elements.
3. Similarly, .childNodes
can hold any node because it is a NodeList https://dom.spec.whatwg.org/#interface-nodelist.
4. Or .innerText https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/innerText. See the differences here https://stackoverflow.com/questions/35213147/difference-between-textcontent-vs-innertext or here https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent#Differences_from_innerText.