Home > Web Front-end > JS Tutorial > How to Extract Specific Text from an HTML Element While Preserving Other Elements?

How to Extract Specific Text from an HTML Element While Preserving Other Elements?

Mary-Kate Olsen
Release: 2024-12-06 05:40:14
Original
680 people have browsed it

How to Extract Specific Text from an HTML Element While Preserving Other Elements?

Extracting Specific Text from an Element with Cross-Browser Compatibility

To retrieve a specific text node from an element while preserving other elements within it, consider the following scenario:

<div>   I am text node<br>   <a></div><br>

Objective: Obtain the text "I am text node" without removing the "Edit" link.

Solution:

The following jQuery code efficiently extracts the text node of interest while maintaining cross-browser compatibility:

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

This code:

  1. Selects the element with the class "title" using jQuery.
  2. Calls the contents() method to retrieve all child elements, including text nodes.
  3. Applies a filter function on these contents to retain only text nodes.
  4. Converts the filtered text nodes into a single string using the text() method.

As a result, the text "I am text node" is returned without affecting the "Edit" link.

The above is the detailed content of How to Extract Specific Text from an HTML Element While Preserving Other Elements?. 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