Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
235 views
in Technique[技术] by (71.8m points)

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 !

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...