Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract the Text in a Element with JQuery

I want to extract the Text inside a Element with JQuery

<div id="bla">
    <span><strong>bla bla bla</strong>I want this text</span>
</div>

I want only the text "I want this text" without the strong-tag. How can I do that?

like image 275
f00860 Avatar asked Jun 19 '09 10:06

f00860


2 Answers

Try this...

<script type="text/javascript">
//<![CDATA[
$(document).ready(function(){
    $("#bla span").contents().each(function(i) {
        if(this.nodeName == "#text") alert(this.textContent);
    });
});

//]]>
</script>

This doesn't need to remove any other nodes from context, and will just give you the text node(s) on each iteration.

like image 72
Kieran Hall Avatar answered Oct 14 '22 15:10

Kieran Hall


Variation on karim79's method:

$("span").clone().find("strong").remove().end().text();

or if you just want the root text without knowing what other tags are in it:

$("span").clone().children().remove().end().text();

still a little long, but I think this about as short as you can hope for.

like image 27
cobbal Avatar answered Oct 14 '22 14:10

cobbal