Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 !

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
225 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...