English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
firstElementChildRead-only property returns the first child element of the specified parent element.
If the parent element has no child elements, this method will returnnullvalue.
UsechildrenProperty returns any child element of the specified parent element. children [0] will return the same result as firstElementChild.
To return the last child element of the specified parent element, uselastElementChildProperty.
ParentElement.firstElementChild
<div> <p>This is the first paragraph in the DIV:</p>1a P</p> <p>This is the first paragraph in the DIV:</p>2a P</p> <p>This is the first paragraph in the DIV:</p>3a P</p> </div> <script> var x = document.querySelector("div").firstElementChild.nodeName; document.getElementById("result").innerHTML = x; </script>Test and See‹/›
All browsers fully support the firstElementChild property:
Property | |||||
firstElementChild | is | is | is | is | is |
Return value: | A Node object representing the first child element of the specified parent element; if there are no child elements, it isnull |
---|---|
DOM Version: | DOM Level1 |
Get the HTML content of the first child element of the DIV element:
<div> <p>This is the first paragraph in the DIV:</p>1a P</p> <p>This is the first paragraph in the DIV:</p>2a P</p> <p>This is the first paragraph in the DIV:</p>3a P</p> </div> <script> var x = document.querySelector("div").firstElementChild.textContent; document.getElementById("result").innerHTML = x; </script>Test and See‹/›
Change the HTML content of the first child element of the DIV element:
var div = document.querySelector("div"); div.firstElementChild.textContent = "HELLO WORLD";Test and See‹/›
HTML DOM Reference:lastElementChild property