textContent, to get and set the text contents of an HTML element and all its child nodes.
If you set a new value of
textContent, all child nodes will be removed and replaced with a single text node containing the specified string.
Let us say we have the following
<p id="intro">My name is <b>John Doe</b>!</p>
The following example shows how to get the text content of the above element:
// grab element const elem = document.querySelector('#intro'); // get text content console.log(elem.innerText); // OR console.log(elem.textContent); // My name is John Doe!
To replace the existing text contents completely, just set a new value for
// replace existing text elem.innerText = 'Hey there! I am Atta';
innerText property is very much similar to the
textContent property. However, there are certain differences:
innerTextreturns the text contents all elements except
textContentreturns text contents of all elements.
innerTextcan not be used to get text contents of elements that are hidden with CSS, but
textContentcan be used.
👋 If you enjoy reading my articles and want to support me to continue creating free tutorials, ☕ Buy me a coffee (cost $5) .
Need help to launch a new product? I am available for contract work. Hire me to accomplish your business goals with engineering and design.