1

Is there a succint way of getting just the text in a div, that also has child elements in it, using jQuery?

For example - how would I extract "Some text" from the html below:

<div id="mydiv">
   <img src="...
   Some text
</div>
Graham
  • 7,807
  • 20
  • 69
  • 114

3 Answers3

2
var text = $("#mydiv")
               .clone()    //clone the element
               .children() //select all the children
               .remove()   //remove all the children
               .end()      //go back to selected element
               .text();    //get the text of element
Johan
  • 35,120
  • 54
  • 178
  • 293
  • This works and is also very instructive, but certainly not as succinct as I would have liked it – Graham Jan 10 '13 at 11:09
  • @Graham I agree, it would be nice if jQuery included some overloads for the text() method that removed the childrens text. But since it doesn't exist at the moment, you need to do something like this. – Johan Jan 10 '13 at 11:23
0

I tried your example with

$('#mydiv').text();

and it worked fine for me!

Enthusiasmus
  • 303
  • 2
  • 9
  • This takes all the html of the div. I'm using version 1.7.1 – Graham Jan 10 '13 at 11:08
  • This only works because img has no text in it. Using an element with text in it instead will also return the text in that element. – Graham Jan 10 '13 at 11:44
0

Using .text() function to any element will extract the text within that tag

$("#elementname").text(); will work

here is the sampe Demo