Home >Web Front-end >JS Tutorial >How to Get Text Content from a Div Element Using Plain JavaScript?

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

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

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);
}

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);
}

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>

Using the "innerHTML" property will return the following:

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

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

However, utilizing the "textContent" property will yield:

textContent = node.textContent;
// textContent = "Some sample text."

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!

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