Categories
JavaScript Answers

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

Spread the love

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

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

Get the Text Node After an HTML Element with JavaScript

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' .

Conclusion

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.

Leave a Reply

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