JavaScript - get last child text

0 points
Created by:

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>
    <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>
      function getLastChildText() {
        var lastChild = document.querySelector('#myList').lastChild; // get last child
        var lastChildText = lastChild.innerHTML; // get last child text


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.

Alternative titles

  1. JavaScript - select last child
  2. JavaScript - get last child inner HTML
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
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.

❤️💻 🙂