Tag Using JavaScript?-JS Tutorial-php.cn">

Home  >  Article  >  Web Front-end  >  How to Resolve \"Undefined\" Result When Retrieving Text from a

Tag Using JavaScript?

How to Resolve \"Undefined\" Result When Retrieving Text from a
Tag Using JavaScript?

Susan Sarandon
Susan SarandonOriginal
2024-10-18 21:14:03275browse

How to Resolve 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

tag using JavaScript, the "undefined" value may appear. To rectify this issue, consider employing textContent instead of innerHTML.

Unlike innerHTML, which captures all DOM content into a string, textContent exclusively retrieves the text within the

. For instance, if the following markup exists:

<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:

  • [textContent](https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent)
  • [innerHTML](https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML)

The above is the detailed content of How to Resolve \"Undefined\" Result When Retrieving Text from a

Tag Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn