Graham
Graham

Reputation: 8181

jQuery select just the text in a div

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>

Upvotes: 1

Views: 196

Answers (3)

Malith Dilanka
Malith Dilanka

Reputation: 26

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

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

here is the sampe Demo

Upvotes: 0

Enthusiasmus
Enthusiasmus

Reputation: 343

I tried your example with

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

and it worked fine for me!

Upvotes: 0

Johan
Johan

Reputation: 35213

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

Upvotes: 2

Related Questions