Languages
[Edit]
EN

JavaScript - get last child text

0 points
Created by:
Dirask Community
6300

In this article, we would like to show you how to select last child and get its text in JavaScript.

Quick solution:

// get last child element by id
var lastChild = document.querySelector('#myList').lastChild;

// get last child text
var lastChildText = lastChild.innerHTML;

 

Practical example

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:

// 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="getLastChildText()">Get last child elements text</button>
    <script>
      function getLastChildText() {
        var lastChild = document.querySelector('#myList').lastChild; // get last child
        var lastChildText = lastChild.innerHTML; // get last child text
        console.log(lastChildText);
      }
    </script>
  </body>
</html>

Note:

For the getLastChildText() function to work properly, there must be no whitespace characters at the end of myList (space, newline, etc.)

It means even the </ul> closing tag must be right after the last child (<li></li>) element.

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join