Home > Web Front-end > JS Tutorial > How to Remove HTML Tags and Extract Pure Text with JavaScript?

How to Remove HTML Tags and Extract Pure Text with JavaScript?

Patricia Arquette
Release: 2024-10-29 22:53:02
Original
1018 people have browsed it

How to Remove HTML Tags and Extract Pure Text with JavaScript?

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:

  1. Identify the HTML element.
    You can use the getElementById() method to get the element you want to extract the text from. In this case, you have an element with id="txt".
  2. 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>
      Copy after login
    • textContent:

      <code class="javascript">var text = element.textContent;</code>
      Copy after login
  3. 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>
    Copy after login

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

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!

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