How to get the text inside an li element when it’s clicked with JavaScript?

Sometimes, we want to get the text inside an li element when it’s clicked with JavaScript.

In this article, we’ll look at how to get the text inside an li element when it’s clicked with JavaScript.

How to get the text inside an li element when it’s clicked with JavaScript?

To get the text inside an li element when it’s clicked with JavaScript, we can listen to the click event on the document.

Then if an li is clicked, we get the text.

For instance, we write:

<ul>
  <li>foo</li>
  <li>bar</li>
  <li>baz</li>
</ul>

to add some li elements.

Then we write:

document.onclick = (e) => {
  if (e.target.tagName.toLowerCase() === 'li') {
    console.log(e.target.innerText)
  }
}

to set the document.onclick property to a function that gets the clicked element with the e.target property.

Then we check the tagName of the element that’s clicked to see if it’s 'li'.

If it is, then we get the text of the li element with e.target.innerText.

Conclusion

To get the text inside an li element when it’s clicked with JavaScript, we can listen to the click event on the document.

Then if an li is clicked, we get the text.