EN
JavaScript - get first child text
0
points
In this article, we would like to show you how to select first child and get its text in JavaScript.
Quick solution:
// get first child element by id
var firstChild = document.querySelector('#myList').firstChild;
// get first child text
var firstChildText = firstChild.innerHTML;
Practical example
In this example, we will select the first child from myList
using firstChild
property. Then using innerHTML
property we will get the text contained within the first child element.
Runnable example:
// ONLINE-RUNNER:browser;
<!DOCTYPE html>
<html>
<body>
<p>My list:</p>
<ul id="myList"><li>🍏 Apple</li>
<li>🍌 Banana</li>
<li>🍊 Orange</li>
<li>🍇 Grapes</li>
<li>🍒 Cherry</li>
</ul>
<button onclick="getFirstChildText()">Get first child elements text</button>
<script>
function getFirstChildText() {
var firstChild = document.querySelector('#myList').firstChild; // get first child
var firstChildText = firstChild.innerHTML; // get first child text
console.log(firstChildText);
}
</script>
</body>
</html>
Note:
For the
getFirstChildText()
function to work properly, there must be no whitespace characters at the start ofmyList
(space, newline, etc.)It means even the
<li>
opening tag must be at the start, right after the<ul id="myList">
tag.