Home > Web Front-end > JS Tutorial > How to Extract Text from a
Element Using Pure JavaScript

How to Extract Text from a
Element Using Pure JavaScript

Patricia Arquette
Release: 2024-10-18 21:15:30
Original
935 people have browsed it

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

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

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!

source:php
Tag Using JavaScript?"> Previous article:How to Resolve \"Undefined\" Result When Retrieving 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