Home > Web Front-end > JS Tutorial > body text

How to Get Text Content from a Div Element Using Plain JavaScript?

Barbara Streisand
Release: 2024-10-18 21:12:30
Original
621 people have browsed it

How to Get Text Content from a Div Element Using Plain JavaScript?

Getting Text Content from a Div Element Using Plain JavaScript

In your attempt to retrieve the text within a div using the "value" property, you encountered an issue where "undefined" was returned. To successfully extract the text content using pure JavaScript, you can utilize the following approach:

The "value" property is primarily used with input elements, not div elements. To access the text content of a div, you should leverage either the "innerHTML" or "textContent" properties.

Using the "innerHTML" property:

function test() {
  var t = document.getElementById('superman').innerHTML;
  alert(t);
}
Copy after login

This approach retrieves the entire content within the div, including any HTML tags. However, if your div contains only text, this method is suitable.

Alternatively, consider using the "textContent" property:

function test() {
  var t = document.getElementById('superman').textContent;
  alert(t);
}
Copy after login

The "textContent" property returns exclusively the text content within the div, excluding any HTML tags. This option is particularly useful when dealing with divs that may contain mixed content.

For instance, consider the following HTML:

<div id="test">
  Some <span class="foo">sample</span> text.
</div>
Copy after login

Using the "innerHTML" property will return the following:

var node = document.getElementById('test');

htmlContent = node.innerHTML;
// htmlContent = "Some <span class="foo">sample</span> text."
Copy after login

However, utilizing the "textContent" property will yield:

textContent = node.textContent;
// textContent = "Some sample text."
Copy after login

For further details and usage examples, refer to the comprehensive documentation provided by MDN:

  • [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 Get Text Content from a Div Element Using Plain JavaScript?. 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