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.