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
Release: 2024-10-18 21:12:03
Original
323 people have browsed it

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

Using innerHTML:

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

Using textContent:

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

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!

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