user636525
user636525

Reputation: 3198

Getting a text of Outer DIV using Jquery

I have Outer DIVS like this.

<Input id ="SaveMe" value="Click" type="submit" >
</Input>

<DIV id="DivOne">
    <DIV >First Content
        <DIV>X
        </DIV>
    </DIV>
        <DIV>Second Content
            <DIV>X
            </DIV>
    </DIV>

</DIV>

I would like to loop through outer DIVs and get the text.I am using the JQuery Code.

$("#SaveMe").click(function() {
    $("#DivOne").children().each(function(index, elem) {
        alert($(elem).text());
    });
});

But it shows First Content X ,Second Content X. I was hoping the "each loop" will loop through the outer DIV first and then the inner DIVs.How can i ignore looping through the inner DIVs (the DIVs with content X). http://jsfiddle.net/VVGRc/1/

Thanks !

Upvotes: 0

Views: 1050

Answers (2)

adeneo
adeneo

Reputation: 318212

Filter for textnodes only:

$("#SaveMe").click(function(e) {
    $("#DivOne").children().each(function(index, elem) {
        var text = $(elem).contents().filter(function() {
            return this.nodeType == 3;
        }).text();
        alert(text);
    });
});​

FIDDLE

Upvotes: 2

yunzen
yunzen

Reputation: 33439

http://viralpatel.net/blogs/jquery-get-text-element-without-child-element/

Male a clone. Delete all child.elements of the clone. Return the text content

Upvotes: 1

Related Questions