HTML DOM firstElementChild 属性

htmlweb developmentfront end technology更新于 2024/5/29 7:08:17

HTML DOM firstElementChild 属性用于返回给定元素的第一个子元素。该子元素仅作为元素节点返回。它会忽略文本和注释节点,不考虑它们。这是一个只读属性。

语法

以下是 HTML DOM firstElementChild 属性的语法 −

element.firstElementChild

示例

让我们来看一个 firstElementChild 属性的示例 −

<!DOCTYPE html>
<html>
<head>
<script>
   function eleChild() {
      var ch = document.getElementById("DIV1").firstElementChild.innerHTML;
      document.getElementById("Sample").innerHTML = "The first element child node of the div is :"+ch;
   }
</script>
</body>
</html>
<h1>firstElementChild property</h1>
<div id="DIV1">
<p>This is a p element</p>
<span>This is a span element</span>
</div>
<button onclick="eleChild()">Get Child</button>
<p id="Sample"></p>
</body>
</html>

输出

这将产生以下输出 −

点击"Get Child"方法 −

在上面的例子中 −

我们创建了一个按钮"Get Child",当用户点击该按钮时,它将执行 eleChild() 方法 −

<button onclick="eleChild()>Get Child</button>

eleChild() 函数获取 id 为"DIV1"的 div 的 firstElementChild并将其 innerHTML 属性赋值给变量 ch。由于 firstElementChild 不考虑空格,它将返回 <p> 元素。使用 innerHTML 属性,我们获取 <p> 元素内的文本,并将其显示在 id 为"Sample"的段落中 −

function eleChild() {
   var ch = document.getElementById("DIV1").firstElementChild.innerHTML;
   document.getElementById("Sample").innerHTML = "The first element child node of the div is :"+ch;
}

相关文章


有用资源