Categories
JavaScript Answers

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

Spread the love

To get the text node after an HTML element with JavaScript, we can use the nextsubling.nodeValue property to get the text content of the text node after a given element.

For instance, if we have the following HTML:

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

Then we can get the node value of the element after it by writing:

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

We select the input with:

document.querySelector('input[name="something"]')

Then we use the nextSibling.nodeValue property of it to get the text node value next to it, which is 'All the world' .

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 *