JQuery method to get node and child node text

  • 2020-03-30 03:36:25
  • OfStack

For the following HTML snippet,


<div id="text_test">test text<a href="techbrood.com" rel="external nofollow" >techbrood co.</a></div>

Get node plain text:


var text = $('#text_test').text()

This will get "test text techbrood co." which will read out the text of all nodes of the current element (including children).

If you only want to get the text of the master node, the method is more complicated:


var text = $("#text_test").contents().filter(function() {
return this.nodeType === 3;
}).text();

Gets the text of a child node:


var text = $("#text_test > a").first().contents().filter(function() {
return this.nodeType === 3;
}).text();

Related articles: