You can use a textContent property to get the textual content of an entire tree node, including its descendants. This is especially useful when you’re dealing with trees that are small or have no children at all (such as XML output).
<div id="note"> <span style="display:none">Your hidden text!</span> </div> let hiddenText = document.getElementById('note'); console.log(hiddenText .textContent);
How the above code works:
- First, you’ll need to select the specific div element that contains the hiddenText by using getElementById.
Reading Text content using innerText:
The innerText syntax property looks very simple with just a textContent text.
let hiddenText = document.createElement('span'); console.log(hiddenText.innerText)
textContent vs innerText
The textContent property and the innerText property are both text properties. Still, textContent is typically used for text elements with a parent node, while innerText is typically used for text elements at the top level of an HTML document. textContent extracts text from children of a node, while text content extracts text from all descendants, including text nodes and markup elements.
Which is better to use?
There are situations where textContent is not appropriate, but for the most part, it’s a text content manipulation tool that you don’t want to be without. Here’s when textContent comes in handy:
– text excluding comments
– text nodes and markup elements like headings, paragraphs, etc.
– extracting text from children of a node
In the end, this will come down to personal preference and familiarity with using either property. In my opinion, if something has all of its descendants first and then any children nodes – such as an XML element – text is best extracted with innerText, if something has one or more child nodes that are at the top level of the DOM tree, then probably best to extract text with textContent.
How to set text to an element:
To set the text content of textbox in HTML, you can use the textContent property. The text content between textbox will be replaced with the text provided to textContent property.
“textContent of textbox in HTML”
let textBox = document.createElement(‘textarea’); textBox.setAttribute(‘aria-label’, ‘Text Text’); textBox.setAttribute(‘placeholder’, ‘Type Text’); textBox.textContent = ‘Show your creativity!’;
In this code, the text is set to textContent property of textbox in HTML. Now, the textbox displays the text that you sent it.
Follow us on Facebook