Home  >  Article  >  Web Front-end  >  How to Extract Text from a

Element Using Pure JavaScript

How to Extract Text from a
Element Using Pure JavaScript

Patricia Arquette
Patricia ArquetteOriginal
2024-10-18 21:15:30909browse

How to Extract Text from a <div> Element Using Pure JavaScript Element Using Pure JavaScript" />

How to Extract Text from a
Tag with Pure JavaScript

Problem:
When attempting to retrieve the text of a

element using getElementById('superman').value, the returned result is "undefined."

Solution:
The issue arises because value is not an appropriate property for a

element. Instead, use textContent to get the text within the
.

To illustrate, consider the following code:

<code class="javascript">function test() {
  var t = document.getElementById('superman').textContent;
  alert(t);
}</code>

Compared to innerHTML, which returns the HTML content of the

, textContent provides only the text within the
.

For example, given the following HTML:

<code class="html"><div id="test">
  Some <span class="foo">sample</span> text.
</div></code>

The following results are obtained:

  • innerHTML returns: "Some sample text."
  • textContent returns: "Some sample text."

For more information, refer to the 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 Extract Text from a

Element Using Pure 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