Saturday, 14 July 2012

jQuery: Get the Text of Element without Child Element




<div id="foo">
    A quick brown fox
    <div id="bar">
        jumps over a lazy dog!
    </div>
</div>
 
<script>
    $("#foo").text(); //return "A quick brown fox jumps over a lazy dog!"
</script>

What if you just want “A quick brown fox” and wants to ignore all the child element? Well, here is a simple solution using jQuery.


<script>
    $("#foo")
        .clone()    //clone the element
        .children() //select all the children
        .remove()   //remove all the children
        .end()  //again go back to selected element
        .text();    //get the text of element
</script>

No comments:

Post a Comment