Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the text node of an element?

<div class="title">
   I am text node
   <a class="edit">Edit</a>
</div>

I wish to get the "I am text node", do not wish to remove the "edit" tag, and need a cross browser solution.

like image 602
Val Avatar asked Oct 14 '22 15:10

Val


People also ask

How do I get nodes in text?

To get the text node of an element with JavaScript, we can use the document. createNodeIterator method to iterate through all the text nodes. to select the p element with document. querySelector .

Is text node an element?

HTML Elements are Nodes Texts are nodes. Some elements contain other nodes.

What is a text node?

A text node encapsulates XML character content. A text node can have zero or one parent. The content of a text node can be empty. However, unless the parent of a text node is empty, the content of the text node cannot be an empty string.


1 Answers

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

This gets the contents of the selected element, and applies a filter function to it. The filter function returns only text nodes (i.e. those nodes with nodeType == Node.TEXT_NODE).

like image 99
James Allardice Avatar answered Oct 18 '22 10:10

James Allardice