How to get top most div parent class

不羁岁月 提交于 2019-11-29 11:43:04
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');
Dhaval Marthak

Try this: use .closest()

$('.chat_text').keypress(function(e) {
    if (e.keyCode == '13') {
       var ru = $(this).closest('.culpritClass').attr('class');
       alert(ru);
    }
});

You can either do like this:

var ru = $(this).parents().find('div').eq(0).attr('class');

or like this:

var ru = $(this).parents().find('div:first').attr('class');

Though there are so many ways to do this, you can select the way you like :)

Demo

Since you are reusing the .culpritClass, for the sake of precision and to avoid multiple parent() calls, use the parents() method with the class of that element as its selector:

$('.chat_text').keypress(function(e) {
  if (e.keyCode == '13') {
    alert($(this).parents('.culpritClass').attr('class'));
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>Place the cursor below and press ENTER</h3>
<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>

Try this,

$(this).closest('selector').find('div:first').attr('class');

If you want the parents .culpritClass first element then try this,

 $(this).closest('.culpritClass').find('div:first').attr('class');

You can also use

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

instead of

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

I would go with $(this).parents('.culpritClass') or if you don't "know" the class, but you know that it has 3 parents exactly, then $(this).parent().parent().parent()

The problem in your JS is that the textarea has no prev(), you should change that too parent() and it will work.

$(document).ready( function() {
    $('.chat_text').keypress(function(e) {
        if (e.keyCode == '13') {                
            var ru = $(this).closest("div").parent();               
            alert($(ru).html());
        }
    });

});

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!