admin管理员组文章数量:1134249
var classes = $(this).attr('class').split(' '); // this gets the current element classes
var classes = $(this).parent().attr('class').split(' '); // this gets the parent classes.
The parent in the above situation is an ankor.
If I wanted to get the first parent DIV of $(this) what would the code look like?
var classes = $(this).div:parent().attr('class').split(' '); // just a quick try.
* Basically I want to get the classes of the first parent DIV of $(this).
thx
var classes = $(this).attr('class').split(' '); // this gets the current element classes
var classes = $(this).parent().attr('class').split(' '); // this gets the parent classes.
The parent in the above situation is an ankor.
If I wanted to get the first parent DIV of $(this) what would the code look like?
var classes = $(this).div:parent().attr('class').split(' '); // just a quick try.
* Basically I want to get the classes of the first parent DIV of $(this).
thx
Share Improve this question edited Aug 17, 2011 at 7:33 Tatu Ulmanen 125k34 gold badges189 silver badges185 bronze badges asked Aug 17, 2011 at 7:27 AdamAdam 1,9616 gold badges19 silver badges17 bronze badges5 Answers
Reset to default 190Use .closest()
to traverse up the DOM tree up to the specified selector.
var classes = $(this).parent().closest('div').attr('class').split(' '); // this gets the parent classes.
Use .closest()
, which gets the first ancestor element that matches the given selector 'div'
:
var classes = $(this).closest('div').attr('class').split(' ');
EDIT:
As @Shef noted, .closest()
will return the current element if it happens to be a DIV also. To take that into account, use .parent()
first:
var classes = $(this).parent().closest('div').attr('class').split(' ');
This gets parent if it is a div. Then it gets class.
var div = $(this).parent("div");
var _class = div.attr("class");
two of the best options are
$(this).parent("div:first")
$(this).parent().closest('div')
and of course you can find the class attr by
$(this).parent("div:first").attr("class")
$(this).parent().closest('div').attr("class")
and for you
$(this).parent("div:first").attr("class").split(' ')
$(this).parent().closest('div').attr("class").split(' ')
Keep it simple!
var classes = $(this).parent('div').attr('class');
本文标签: javascriptHow to select first parent DIV using jQueryStack Overflow
版权声明:本文标题:javascript - How to select first parent DIV using jQuery? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736833548a1954804.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论