Reputation: 43673
Let's have html code like this:
<div id="d1"><span>1.</span>Hallo <span>Kitty, </span><div>How are you?</div></div>
It is just example, there may be different children elements inside.
How can I get text inside of d1
container that is not part of children elements?
For the example above it shold be just "Hallo "
Upvotes: 4
Views: 728
Reputation: 7663
this will work for you
$('#d1')
.contents()
.filter(function() {
return this.nodeType == Node.TEXT_NODE;
}).text()
or you can use this as suggested below for old browser support also
var text = $("#d1").contents().filter( function() {
return this.nodeType === 3;
}).text();
Upvotes: 6
Reputation: 92893
Improving on halex's 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
technique, because it's more clear what you're doing.
Upvotes: 2
Reputation: 140230
var text = $("#d1").contents().filter( function() {
return this.nodeType === 3;
}).text();
Upvotes: 5