JavaScript - get first child text

0 points
Created by:

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>
    <p>My list:</p>
    <ul id="myList"><li>🍏 Apple</li>
      <li>🍌 Banana</li>
      <li>🍊 Orange</li>
      <li>🍇 Grapes</li>
      <li>🍒 Cherry</li>
    <button onclick="getFirstChildText()">Get first child elements text</button>
      function getFirstChildText() {
        var firstChild = document.querySelector('#myList').firstChild; // get first child
        var firstChildText = firstChild.innerHTML; // get first child text


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.

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.

â€ïžđŸ’» 🙂