HTML DOM firstElementChild property
HTML DOM的firstElementChild属性用于返回给定元素的第一个子元素。子元素仅作为元素节点返回。它忽略文本和注释节点,并且不考虑它们。这是一个只读属性。
句法
以下是HTML DOM firstElementChild属性的语法-
1 | element.firstElementChild |
例
让我们看一下firstElementChild属性的示例-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | <!DOCTYPE html> <html> <head> function eleChild() { var ch = document.getElementById("DIV1").firstElementChild.innerHTML; document.getElementById("Sample").innerHTML ="The first element child node of the div is :"+ch; } </body> </html> firstElementChild property <p> This is a p element </p> <span>This is a span element</span> <button onclick="eleChild()">Get Child</button> <p id="Sample"> </p> </body> </html> |
输出量
这将产生以下输出-
在点击"获取孩子"方法时-
在上面的示例中-
我们创建了一个"获取子项"按钮,该按钮将在用户点击后执行eleChild()方法-
1 | <button onclick="eleChild()">Get Child</button> |
eleChild()函数获取ID为" DIV1"的div的firstElementChild并将其innerHTML属性分配给变量ch。由于firstElementChild不考虑空格,它将返回
元件。使用innerHTML属性,我们在
中获取文本
元素并将其显示在ID为" Sample"的段落中-
1 2 3 4 | function eleChild() { var ch = document.getElementById("DIV1").firstElementChild.innerHTML; document.getElementById("Sample").innerHTML ="The first element child node of the div is :"+ch; } |