JavaScript Answers

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

Spread the love

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

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.

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 *