EN
JavaScript - get last child text
0 points
In this article, we would like to show you how to select last child and get its text in JavaScript.
Quick solution:
xxxxxxxxxx
1
// get last child element by id
2
var lastChild = document.querySelector('#myList').lastChild;
3
4
// get last child text
5
var lastChildText = lastChild.innerHTML;
In this example, we will select the last child from myList
using lastChild
property. Then using innerHTML
property we will get the text contained within the last child element.
Runnable example:
xxxxxxxxxx
1
2
<html>
3
<body>
4
<p>My list:</p>
5
<ul id="myList">
6
<li>🍏 Apple</li>
7
<li>🍌 Banana</li>
8
<li>🍊 Orange</li>
9
<li>🍇 Grapes</li>
10
<li>🍒 Cherry</li></ul>
11
<button onclick="getLastChildText()">Get last child elements text</button>
12
<script>
13
function getLastChildText() {
14
var lastChild = document.querySelector('#myList').lastChild; // get last child
15
var lastChildText = lastChild.innerHTML; // get last child text
16
console.log(lastChildText);
17
}
18
</script>
19
</body>
20
</html>
Note:
For the
getLastChildText()
function to work properly, there must be no whitespace characters at the end ofmyList
(space, newline, etc.)It means even the
</ul>
closing tag must be right after the last child (<li></li>
) element.