1.Hallo Kitty,

How to get text inside a container that is not part of children

Let there be html code:

<div id="d1"><span>1.</span>Hallo <span>Kitty, </span><div>How are you?</div></div> 

This is just an example; there may be different children inside it.

How can I get the text inside the container d1 , which is not part of the children?

In the example above, it's just "Hallo "

+4
source share
3 answers

http://jsfiddle.net/SGZW4/

 var text = $("#d1").contents().filter( function() { return this.nodeType === 3; }).text(); 
+5
source

it will work for you

 $('#d1') .contents() .filter(function() { return this.nodeType == Node.TEXT_NODE; }).text() 

or you can use this as suggested below to support the old browser.

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

Demo

+6
source

Improving the halex trick, you can take advantage of the fact that .children() finds only DOM nodes and ignores text nodes:

 var text = $('#d1').clone().children().remove().end().text(); // string "Hallo " 

... but I prefer the .nodeType method because it is more clear what you are doing.

+2
source

Source: https://habr.com/ru/post/1438895/


All Articles