Home >Web Front-end >JS Tutorial >How Can I Retrieve Div Tag Text Using JavaScript (Without jQuery)?

How Can I Retrieve Div Tag Text Using JavaScript (Without jQuery)?

Barbara Streisand
Barbara StreisandOriginal
2024-10-18 21:12:03314browse

How Can I Retrieve Div Tag Text Using JavaScript (Without jQuery)?

How to Retrieve Div Tag Text Using JavaScript (Without jQuery)

To obtain the text content of a div element solely with JavaScript, there are alternatives to jQuery.

Problem Statement:

A previous attempt to retrieve the text using document.getElementById('superman').value returned undefined. The goal is to find a solution using plain JavaScript without jQuery.

Solution:

To successfully retrieve the text, consider using textContent instead of value. The innerHTML property returns the entire DOM content as a string, including elements within the div. In contrast, textContent specifically extracts the text within the div, ensuring a more accurate text representation.

For instance, given the following HTML:

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

Using innerHTML:

<code class="javascript">var node = document.getElementById('test');
var htmlContent = node.innerHTML;
// htmlContent = "Some <span class="foo">sample</span> text."</code>

Using textContent:

<code class="javascript">var node = document.getElementById('test');
var textContent = node.textContent;
// textContent = "Some sample text."</code>

Refer to MDN for more information on textContent and innerHTML:

  • [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 Can I Retrieve Div Tag Text Using JavaScript (Without jQuery)?. 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