Categories
JavaScript Answers

How to Get the Text Node After an Element with JavaScript?

Spread the love

Sometimes, we want to get the text node after an element with JavaScript.

In this article, we’ll look at how to get the text node after an element with JavaScript.

Get the Text Node After an Element with JavaScript

To get the text node after an element with JavaScript, we can use the nextSibling property to get the the text node after an element.

For instance, if we have:

<input type="checkbox" name='something' value='v1' /> hello world <br />

Then we write:

const text = document
  .querySelector('input[name="something"]')
  .nextSibling.nodeValue;
console.log(text)

We call document.querySelector with the selector string of the checkbox input to select it.

Then we get the value of the text node next to the checkbox with the nextSibling.nodeValue

Therefore, text is hello world according to the console log.

Conclusion

To get the text node after an element with JavaScript, we can use the nextSibling property to get the the text node after an element.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *