Home >Web Front-end >JS Tutorial >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>
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();
This code:
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!