Home >Web Front-end >JS Tutorial >How Can I Extract Text Nodes from an Element Without Modifying the DOM?

How Can I Extract Text Nodes from an Element Without Modifying the DOM?

DDD
DDDOriginal
2024-12-03 21:43:09200browse

How Can I Extract Text Nodes from an Element Without Modifying the DOM?

Retrieving Text Nodes without Altering DOM Structure

In certain scenarios, it becomes necessary to extract the text content of an element without modifying its structure. For example, in the following HTML code:

<div>

If the desired output is to obtain the text "I am text node" while preserving the "edit" tag, a cross-browser solution is required.

Utilizing JavaScript's Element.contents() and Node.TEXT_NODE

To achieve this, we can leverage JavaScript's Element.contents() and Node.TEXT_NODE properties. Here's a concise yet effective code snippet:

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

Breaking Down the Solution:

  • $(".title").contents(): This function returns a collection of all direct child nodes within the selected element with class "title".
  • .filter(): The filter function loops through each child node and returns only those that are of type Node.TEXT_NODE.
  • .text(): This method extracts the text content of the filtered result.

Therefore, using this technique, we can successfully obtain the "I am text node" portion without altering the HTML structure. This solution is compatible with all major web browsers, ensuring cross-browser functionality.

The above is the detailed content of How Can I Extract Text Nodes from an Element Without Modifying the DOM?. 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