Skip to content Skip to sidebar Skip to footer

Javascript - Check If Element Directly Contains Any Text

I would like to know if an element contains any text directly. By directly I mean: not through its children.
text-in-div<

Solution 1:

if you just want “ Any String ” 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>

We clone the element that you want text of, then remove all the child elements from this cloned element and then returns the text of element.


Post a Comment for "Javascript - Check If Element Directly Contains Any Text"