How to get text from an element with other children using jQuery

I have something similar to the following:

<div> Hello World <div>Something Else</div> </div> 

I want to use javascript / jQuery to get the text "Hello World". I could just wrap it in between and select it, but now I want to know how to do it.

I thought to just use $ ('div'). text () will work, but it gives me "Hello WorldSomething Else".

Thanks Matt

+4
source share
5 answers

Try the following:

 var div = document.getElementsByTagName('div')[0].firstChild; var text = div.textContent ? div.textContent.trim() : div.innerText; 

Fiddle

Note that IE8 and earlier do not support the trim function; if you use jQuery, you can use the jQuery $.trim() utility function, which is a cross-browser. $.trim(text)

+2
source

text() , as you discovered, receives the text not only of the target node (s), but also of any child / stream nodes.

Even if it weren’t, your code in its current form would still return the concatenation of both parts of the text, because your selector is just a div , so jQuery will search for all div and get their text as one piece of text.

You can get the immediate text of an element with just something similar, although there are other ways.

 //make a mini plugin for getting the immediate text of an element $.fn.extend({ immediateText: function() { return this.clone().find("*").remove().end().text(); } }); //use the plugin var immediateText = $('#some_element').immediateText(); 
+1
source

Sorry if this is too similar to @minitech's answer:

 var text = $('div:first') .contents() .filter(function() { return (this.nodeType === 3); }).text(); alert(text);​ 

You can use a combination of contents() (gets the contents of the selected elements) and filter() to reduce the matched set only by text ( nodetype === 3 means "Text").

jsFiddle

Of course, you could use first() if you were sure what your html would look like:

 var text = $('div:first') .contents() .first() .text(); 

jsFiddle

+1
source

Use .contents :

 yourDiv.contents().filter(function() { return this.nodeType === 3; }).map(function() { return this.nodeValue; }).get().join(''); 

Alternatively, sans jQuery:

 var i, c, result = ''; for(i = 0; c = yourDiv.childNodes[i]; i++) { if(c.nodeType === 3) { result += c.nodeValue; } } 
0
source

Clone an element (first div), remove all child elements and get the text, optionally remove spaces with $.trim() :

 var elm = $('div:first').clone(); var text = $.trim(elm.children().remove().end().text()); 

Fiddle

0
source

All Articles