Home >Web Front-end >JS Tutorial >How Can I 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.
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.
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>
Using innerHTML:
<code class="javascript">var node = document.getElementById('test'); var htmlContent = node.innerHTML; // htmlContent = "Some <span class="foo">sample</span> text."</code>
Using textContent:
<code class="javascript">var node = document.getElementById('test'); var textContent = node.textContent; // textContent = "Some sample text."</code>
Refer to MDN for more information on textContent and 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!