Home > Web Front-end > JS Tutorial > How to Retrieve Only Text Node Content from an HTML Element Cross-Browser?

How to Retrieve Only Text Node Content from an HTML Element Cross-Browser?

Linda Hamilton
Release: 2024-12-03 09:45:13
Original
1080 people have browsed it

How to Retrieve Only Text Node Content from an HTML Element Cross-Browser?

Retrieving Element Text Node Cross-Browser

In HTML, obtaining the text content of an element can be tricky when it contains both text and other elements. To effectively extract the text node, a cross-browser solution is required.

Problem:

Consider the following HTML structure:

<div class="title">
   I am text node
   <a class="edit">Edit</a>
</div>
Copy after login

The goal is to retrieve the text node "I am text node," while preserving the "Edit" anchor tag.

Solution:

This can be achieved using the jQuery framework:

var text = $(".title").contents().filter(function() {
  return this.nodeType == Node.TEXT_NODE;
}).text();
Copy after login

This code:

  1. Selects the element with the "title" class.
  2. Gets its contents using the contents() method.
  3. Filters the contents using the filter() method, keeping only text nodes (nodeType == Node.TEXT_NODE).
  4. Retrieves the text content of the filtered nodes using the text() method.

As a result, the variable text will contain only the desired text node, "I am text node."

The above is the detailed content of How to Retrieve Only Text Node Content from an HTML Element Cross-Browser?. 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