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:
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!