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:
xxxxxxxxxx
1
// get first child element by id
2
var firstChild = document.querySelector('#myList').firstChild;
3
4
// get first child text
5
var firstChildText = firstChild.innerHTML;
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:
xxxxxxxxxx
1
2
<html>
3
<body>
4
<p>My list:</p>
5
<ul id="myList"><li>🍏 Apple</li>
6
<li>🍌 Banana</li>
7
<li>🍊 Orange</li>
8
<li>🍇 Grapes</li>
9
<li>🍒 Cherry</li>
10
</ul>
11
<button onclick="getFirstChildText()">Get first child elements text</button>
12
<script>
13
function getFirstChildText() {
14
var firstChild = document.querySelector('#myList').firstChild; // get first child
15
var firstChildText = firstChild.innerHTML; // get first child text
16
console.log(firstChildText);
17
}
18
</script>
19
</body>
20
</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.