例 (Example)
var kids = node.childNodes;
In the example above, kids will be a collection of all the direct child nodes of node. If node has no child nodes then kids will be an empty collection (with zero length). The returned collection is live, which means that changes to the HTML it represents are immediately reflected in the collection, without having to retrieve it again.
在上面的示例中, 孩子将是node的所有直接子节点的集合。 如果节点没有子节点,那么孩子将是一个空的集合(长度为零)。 返回的集合是live ,这意味着对它表示HTML的更改将立即反映在该集合中,而无需再次检索它。
So if we say that node is actually an HTML ul
element, like this:
因此,如果我们说该节点实际上是一个HTML ul
元素,如下所示:
<ul>
<li>Mostly set in 1955 <em>(Part 1)</em></li>
<li>Mostly set in 2015 <em>(Part 2)</em></li>
<li>Mostly set in 1885 <em>(Part 3)</em></li>
</ul>
Each of those li
elements is a child node of the ul
, and will be included in its childNodes
collection, numbered 0
to 2
. The em
elements will not be in that collection, because they’re not direct child nodes of the list (they are descendents, not children).
这些li
元素中的每一个都是ul
的子节点,并将包含在其childNodes
集合中,编号为0
到2
。 该em
元素不会是收藏,因为它们不在名单的直接子节点(它们的后代 ,没有孩子)。
Actually this example is idealized, and in some browsers there may in fact be additional nodes in the childNodes
collection; that’s because some browsers count intermediate whitespace as text nodes, and would therefore consider each piece of whitespace between the structural nodes to be a text node.
实际上,该示例是理想化的,在某些浏览器中,实际上childNodes
集合中可能还有其他节点; 这是因为某些浏览器将中间空白视为文本节点,因此将结构节点之间的每个空白都视为一个文本节点。
For more about this behavior please see DOM Core.
有关此行为的更多信息,请参见DOM Core 。
描述 (Description)
The childNodes collection is an ordered list of all the direct child nodes of this node; if there are no child nodes then this collection is empty (it has zero length). The childNodes collection is a NodeList, in which the items are indexed numerically, and appear in source order.
childNodes集合是此节点的所有直接子节点的有序列表。 如果没有子节点,则此集合为空(长度为零)。 childNodes集合是一个NodeList ,其中的项目将按数字进行索引,并按源顺序显示。
As with all node lists, childNodes is a live collection, which means that changes to the collection it represents are immediately reflected in the node list (as opposed to it being a static snapshot).
与所有节点列表一样,childNodes是一个实时集合,这意味着对它表示的集合的更改将立即反映在节点列表中(与之相反,它是静态快照)。
Attributes of an element are not considered child nodes, and therefore don’t appear in the childNodes collection2
元素的属性不视为子节点,因此不会出现在childNodes集合中2
This collection is read only.
该集合是只读的。
集合不是数组 (A collection is not an array)
Even though a collection looks like an array, it isn’t an array — although you can iterate through it and refer to its members like an array, you can’t use Array methods like push or pop on it.
即使一个集合看起来像一个数组,它也不是一个数组-尽管您可以遍历它并像数组一样引用它的成员,但是不能在其上使用push或pop这样的Array方法。
翻译自: https://www.sitepoint.com/childnodes-w3c-dom-core-property/