Home >Web Front-end >JS Tutorial >How to Resolve \'Undefined\' Result When Retrieving Text from a
Tag Using JavaScript?" /> Tag Using JavaScript?" />
Obtaining Text Content from a DIV Tag Using Pure JavaScript
If attempting to retrieve the text content of a
Unlike innerHTML, which captures all DOM content into a string, textContent exclusively retrieves the text within the
<code class="html"><div id="test"> Some <span class="foo">sample</span> text. </div></code>
Using innerHTML would yield:
<code class="js">var node = document.getElementById('test'); var htmlContent = node.innerHTML; // htmlContent = "Some <span class="foo">sample</span> text."</code>
Whereas textContent provides:
<code class="js">var textContent = node.textContent; // textContent = "Some sample text."</code>
This distinction is crucial when handling DOM content that may include both text and non-text elements.
For additional information, refer to the Mozilla Developer Network (MDN) documentation on:
The above is the detailed content of How to Resolve 'Undefined' Result When Retrieving Text from a