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
914 views
in Technique[技术] by (71.8m points)

jquery - How to get top most div parent class

I need to get the main culpritClass div class that holds everything after something is typed and enter is pressed and put it into a variable as a string.

I can't seem to get the class.

HTML:

<div class="culpritClass">
<div class="inner" style="display: block;">
<div class="inner_chat"></div>
<form>
<textarea class="chat_text"></textarea> 
</form>     
</div><a class="culpritClass" href="#">culprit</a>
</div>

I tried the following JS but I get undefined.

$('.chat_text').keypress(function(e) {
    if (e.keyCode == '13') {

        var ru = $(this).prev().parent().attr('class');

        alert(ru);
    }
});

The var ru is the line that matters.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)
var ru = $(this).parent().parent().parent().attr('class');

should do the trick. Even though this doesn't look like it is the neatest solution, it is the most straightforward one imo. Unless there's a function to pass an argument to a function which travels a number up, e.g. ancestor(3) which would travel three levels up in the DOM and return that element.

But if you are just trying to find the class itself, try closest.

var ru = $(this).closest('.culpritClass');

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

...