"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Retrieve Div Tag Text Using JavaScript (Without jQuery)?

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

Published on 2024-11-06
Browse:384

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:

Some sample text.

Using innerHTML:

var node = document.getElementById('test');
var htmlContent = node.innerHTML;
// htmlContent = "Some sample text."

Using textContent:

var node = document.getElementById('test');
var textContent = node.textContent;
// textContent = "Some sample text."

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)
Release Statement This article is reprinted at: 1729257018 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3