How to Extract Pure Text from HTML with JavaScript
To extract the pure text from a HTML element without the HTML tags, follow these steps using JavaScript:
Get the text content.
There are two ways to get the text content from an HTML element: innerText and textContent. innerText returns the visible text content, while textContent returns all text content, even if it's hidden. In this case, you can use either method. Here's how you would use them:
innerText:
<code class="javascript">var text = element.innerText;</code>
textContent:
<code class="javascript">var text = element.textContent;</code>
Replace the HTML with the text.
Once you have the text content, you can replace the HTML content of the element with the text content. Here's how you would do that:
<code class="javascript">element.innerHTML = text;</code>
Here's the complete JavaScript function that you can use:
<code class="javascript">var element = document.getElementById('txt'); var text = element.innerText || element.textContent; element.innerHTML = text;</code>
When the user clicks the "Get Content" button, this JavaScript function will be executed, and the HTML content within the p element with id="txt" will be replaced with the pure text content.
The above is the detailed content of How to Remove HTML Tags and Extract Pure Text with JavaScript?. For more information, please follow other related articles on the PHP Chinese website!