HTML DOM Element childNodes property

Definition and usage

childNodes The property returns a collection (list) of element child nodes.

childNodes The property returns a NodeList object.

childNodes The property is read-only.

childNodes[0] Same as firstChild.

Hint

childNodes Returns node: element node, text node, and comment node.

Whitespace between elements is also a text node.

Alternative:

children property - children The property returns child elements (ignores text and comments).

See also:

firstChild property

lastChild property

nextSibling property

previousSibling property

hasChildNodes() method

Node properties

parentNode property

nodeName property

nodeType属性

nodeValue属性

HTML节点与元素

HTML DOM(文档对象模型)中,HTML文档是拥有(或没有)子节点的节点集合。

节点指的是元素节点、文本节点和注释节点。

元素之间的空白也是文本节点。

而元素只是元素节点。

子节点与子元素

childNodes 返回子节点(元素节点、文本节点和注释节点)。

children 返回子元素(而非文本和注释节点)。

同胞与元素同胞

同胞是“兄弟”和“姐妹”。

同胞是拥有相同父节点的节点(在相同的 childNodes 列表中)。

元素同胞是拥有相同父元素的元素(在相同的 children 列表中)。

实例

例子1

获取<body>元素的子节点:

const nodeList = document.body.childNodes;

亲自试一试

例子2

获取"myDIV"中的子节点数:

let numb = document.getElementById("myDIV").childNodes.length;

亲自试一试

例子3

更改第二个子节点的背景颜色:

element.childNodes[1].style.backgroundColor = "yellow";

亲自试一试

例子4

获取<select>元素的第三个子节点的文本:

let text = document.getElementById("mySelect").childNodes[2].text;

亲自试一试

语法

element.childNodes

返回值

类型 描述
对象

节点的NodeList对象集合。

节点按照它们在文档中出现的顺序进行排序。

浏览器支持

element.childNodes 是DOM Level 1 (1998)特性。

所有浏览器都完全支持它:

Chrome IE Edge Firefox Safari Opera
Chrome IE Edge Firefox Safari Opera
支持 9-11 支持 支持 支持 支持