How to Extract Pure Text from HTML Elements Using JavaScript
When dealing with HTML elements that contain both text and markup, it's often desirable to obtain the text content without HTML elements. This can be achieved using JavaScript, as demonstrated in the following example.
In the provided HTML snippet, we have a button with onclick event that triggers a JavaScript function, which is tasked with extracting the text content from a
element and removing the HTML elements.
Expected Result:
When the user clicks the button, the HTML elements within the
element will be removed, leaving only the pure text content.
JavaScript Function:
The following JavaScript function uses the innerText property to extract the text content from the
element:
<code class="javascript">function get_content() { // Retrieve the <p> element by its ID var element = document.getElementById('txt'); // Extract the text content using innerText var text = element.innerText || element.textContent; // Update the HTML content of the <p> element with the extracted text element.innerHTML = text; }</code>
Explanation:
element is updated with the extracted text, effectively removing the HTML elements.
The above is the detailed content of How can I extract pure text from HTML elements using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!