Home > Web Front-end > JS Tutorial > body text

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

Susan Sarandon
Release: 2024-10-18 21:14:03
Original
276 people have browsed it

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>
Copy after login

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>
Copy after login

Whereas textContent provides:

<code class="js">var textContent = node.textContent;
// textContent = "Some sample text."</code>
Copy after login

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!

source:php
Previous article:How to Retrieve Text from Div Tags in JavaScript without jQuery? Next article:How to Extract Text from a
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template