To set and get the text content of an element and its descendants, you use the textContent
property of the element:
element.textContent
Code language: CSS (css)
Note that the textContent
strips all HTML tags before returning it.
The following example returns the text content of the element whose id is container
:
const el = document.querySelector('#container');
console.log(el.textContent);
Code language: JavaScript (javascript)
And the following sets the text content of the container element:
const el = document.querySelector('#container');
el.textContent = 'Just simple text';
Code language: JavaScript (javascript)
Most modern web browsers support the textContent
property. IE8 uses the innerText
instead.
If your web application supports IE8, you can use the following code to get the text content of an element:
const el = document.querySelector('#container');
const text = el.textContent || el.innerText;
Code language: JavaScript (javascript)
Was this tutorial helpful ?