Languages
[Edit]
EN

JavaScript - get first child text

0 points
Created by:
Zayaan-Rasmussen
533

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 of myList (space, newline, etc.)

It means even the <li> opening tag must be at the start, right after the <ul id="myList"> tag.

Alternative titles

  1. JavaScript - select first child
  2. JavaScript - get first 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.

❤️💻 🙂

Join