Home  >  Article  >  Web Front-end  >  How to Extract Pure Text from HTML Elements using JavaScript?

How to Extract Pure Text from HTML Elements using JavaScript?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-31 15:35:02648browse

How to Extract Pure Text from HTML Elements using JavaScript?

Extracting Pure Text from HTML Elements with JavaScript

When working with HTML pages, it's often necessary to extract the pure text content without the surrounding HTML elements. This can be achieved using JavaScript.

In this scenario, you have an HTML page with a button and some text enclosed within a

element. When the button is clicked, the HTML markup should be stripped, leaving the pure text unaltered.

To accomplish this, you can utilize the following JavaScript function:

<code class="javascript">var element = document.getElementById('txt');
var text = element.innerText || element.textContent;
element.innerHTML = text;</code>

The document.getElementById('txt') line retrieves the

element with the ID 'txt'.

The innerText or textContent property can be used to fetch the text content within the element. innerText approximates the visible text (excluding tags), while textContent strictly removes HTML tags. Choose the property that best suits your requirements.

Finally, element.innerHTML = text replaces the HTML content within the

with the pure text value.

By utilizing this technique, you can effectively extract pure text from HTML elements, allowing you to manipulate text content as needed.

The above is the detailed content of How to Extract Pure Text from HTML Elements using 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