Home > Web Front-end > JS Tutorial > body text

How can I extract pure text from HTML elements using JavaScript?

Susan Sarandon
Release: 2024-10-31 18:48:02
Original
562 people have browsed it

How can I extract pure text from HTML elements using JavaScript?

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>
Copy after login

Explanation:

  • The innerText property returns the text content of an element, excluding any HTML elements within it.
  • If the element doesn't have an innerText property (older browsers), the textContent property can be used instead.
  • Finally, the HTML content of the

    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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!