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:
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!