Getting the Text Node of an Element
When working with HTML elements in JavaScript, it's often necessary to obtain the text content within those elements. However, elements can contain various types of nodes, including text nodes, comment nodes, and element nodes. This article explores a cross-browser solution for retrieving the text node.
Consider the following HTML:
<div class="title"> I am text node <a class="edit">Edit</a> </div>
Our goal is to obtain the "I am text node" content while preserving the "Edit" link.
To accomplish this, we can utilize jQuery's contents() and filter() functions:
var text = $(".title").contents().filter(function() { return this.nodeType == Node.TEXT_NODE; }).text();
This code selects the element with the class "title" and obtains its contents. Then, it applies a filter function to the contents, selecting only nodes with a nodeType of Node.TEXT_NODE (i.e., text nodes). Finally, it extracts the text content from the filtered result.
Using this approach, we can successfully retrieve the desired text node content without removing the "Edit" tag.
The above is the detailed content of How to Extract Text Node Content from an HTML Element in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!