How to get only direct text without tags with jQuery

How to get only direct text without tags with jQuery

This is tricky, because the text is in a text node, and jQuery doesn’t support text nodes, only elements. Also because different browsers treat white space in HTML code differently, so you end up with different sets of nodes in different browsers. You can’t just get the nodes and rely on that the text node that you want is at the same index all the time.

You can use jQuery to locate an element, and use the DOM to get all the nodes inside it.

Example HTML:

1) TEXT THAT I ONLY NEED

some par

  • asdf
  • qwerty

Use jQuery to find the div, use [0] to get the DOM element out of the jQuery object, and the childNodes property to get its children:

var nodes = $(‘#test’)[0].childNodes;

Then you can use jQuery to loop through the nodes to find the node that is the strong element:

var index; $.each(nodes, function(i,e){ if (e.tagName == ‘STRONG’) { index = i; return false; } });

Now you can use the DOM to get the text value from the next node:

var text = nodes[index + 1].nodeValue;

Source

Leave a Reply