EN
JavaScript - get text node of HTML element
0
points
In this article, we would like to show you how to get the text node of the HTML element using JavaScript.
1. Practical example
In this example, we present how to get the text node of the container
element and display its value in the console.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<div id="container">Example text...</div>
<script>
let container = document.querySelector('#container');
let text = container.childNodes[0];
console.log(text.nodeValue);
</script>
</body>
</html>
Note:
You can also use
textContent
instead ofnodeValue
to get text from the text node.
2. More complex example
In this section, we present a more complex example of how to get the text node and display its value when we have some nested elements.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<div id="container">Text-1<span>Text-2</span></div>
<script>
let text1 = document.querySelector('#container').childNodes[0];
let text2 = document.querySelector('#container span').childNodes[0];
// or:
// let text2 = document.querySelector('#container').childNodes[1].childNodes[0];
console.log(text1.nodeValue); // Text-1
console.log(text2.nodeValue); // Text-2
</script>
</body>
</html>