HTML DOM childElementCount属性

HTML DOM childElementCount Property

HTML DOM childElementCount属性是一个只读属性,它返回给定元素的子元素数。 childElementCount的返回类型为unsigned long。它只会返回在其上被查询的节点的子元素,而不是HTML文档的所有子节点。

句法

以下是childElementCount属性的语法-

1
node.childElementCount

让我们看一下HTML DOM childElementCount属性的示例-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<!DOCTYPE html>
<html>
<head>
<style>
 div {
   border: 2px solid blue;
   margin: 7px;
   padding-left:20px;
 }
</style>
</head>
<body>
<p><center>[wp_ad_camp_2]</center></p><p>
Click the button below to find out the no of children of the div element
</p>
<button onclick="childCount()">COUNT</button>

<p>
HEADING
</p>
<p>
First p element
</p>
<p>
Second p element
</p>

<p id="Sample">
</p>

 function childCount() {
   var x = document.getElementById("myDIV").childElementCount;
   document.getElementById("Sample").innerHTML ="The div element has"+x+" children";
 }

</body>
</html>

输出量

这将产生以下输出-

点击"计数"按钮时-

在上面的示例中-

我们创建了一个id为" myDIV"的元素,并在其中包含三个元素。两个

元素和

标头。我们还在div中添加了彩色边框,边距和填充,以将其与其他元素区分开来-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
div {
 border: 2px solid blue;
 margin: 7px;
 padding-left:20px;
}

<p>
HEADING
</p>
<p>
First p element
</p>
<p>
Second p element
</p>

然后,我们创建了一个按钮COUNT,该按钮将在单击时执行childCount()方法。

1
<button onclick="childCount()">COUNT</button>

childCount()方法采用id为" myDIV"的元素(在我们的情况下为元素),并将其childElementCount属性值分配给变量x。由于我们有两个

元素和

内的元素,因此childElementCount返回3。

然后,在段落上使用innerHTML()方法将返回的值显示在ID为" Sample"的段落中-

1
2
3
4
function childCount() {
 var x = document.getElementById("myDIV").childElementCount;
 document.getElementById("Sample").innerHTML ="The div element has"+x+" children";
}