HTML DOM NodeList length 属性

定义和用法

length 属性返回 NodeList 中的节点数。

length 属性是只读的。

实例

例子 1

获取文档中子节点的数量:

const nodeList = document.body.childNodes;
let number = nodeList.length;

Try it yourself

例子 2

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

const nodeList = document.body.childNodes;

Try it yourself

Example 3

Get the number of child nodes in "myDIV":

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

Try it yourself

Example 4

How many <p> elements are in "myDIV":

const div = document.getElementById("myDIV");
const list = div.querySelectorAll("p");
let number = list.length;

Try it yourself

Example 5

Traverse all <p> elements within "myDIV" and change their font size:

const div = document.getElementById("myDIV");
const list = div.querySelectorAll("p");
for (let i = 0; i < list.length; i++) {
  list[i].style.fontSize = "red";
}

Try it yourself

Example 6

Traverse all child nodes and collect the names of each node:

const list = document.body.childNodes;
let text = "";
for (let i = 0; i < list.length; i++) {
  text += list[i].nodeName + "<br>";
}

Try it yourself

Syntax

nodelist.length

Return value

Type Description
Number Number of nodes in NodeList.

Browser support

nodelist.length is a DOM Level 1 (1998) feature.

All modern browsers support it:

Chrome IE Edge Firefox Safari Opera
Chrome IE Edge Firefox Safari Opera
Support 9-11 Support Support Support Support

Related pages

entries() method

forEach() method

item() method

keys() method

values() method

NodeList object

childNodes() method

querySelectorAll() method

getElementsByName() method