Javascript 如何使用jQuery选择第一个父DIV?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7089229/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:48:12  来源:igfitidea点击:

How to select first parent DIV using jQuery?

javascriptjquerycss-selectors

提问by Adam

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.

上述情况下的父母是 ankor。

If I wanted to get the first parent DIV of $(this) what would the code look like?

如果我想获得 $(this) 的第一个父 DIV,代码会是什么样子?

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).

*基本上我想获取 $(this) 的第一个父 DIV 的类。

thx

谢谢

回答by Shef

Use .closest()to traverse up the DOM tree up to the specified selector.

用于.closest()向上遍历 DOM 树直到指定的选择器。

var classes = $(this).parent().closest('div').attr('class').split(' '); // this gets the parent classes.

回答by Tatu Ulmanen

Use .closest(), which gets the first ancestor element that matches the given selector 'div':

Use .closest(),它获取与给定选择器匹配的第一个祖先元素'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:

正如@Shef 所指出的,.closest()如果它恰好也是一个 DIV ,则将返回当前元素。要考虑到这一点,.parent()请先使用:

var classes = $(this).parent().closest('div').attr('class').split(' ');

回答by Esben

This gets parent if it is a div. Then it gets class.

如果它是一个 div,这将获得父级。然后就上课了。

var div = $(this).parent("div");
var _class = div.attr("class");

回答by Daniel West

Keep it simple!

把事情简单化!

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

回答by Junaid Masood

two of the best options are

两个最好的选择是

$(this).parent("div:first")

$(this).parent().closest('div')

and of course you can find the class attr by

当然,您可以通过以下方式找到类 attr

$(this).parent("div:first").attr("class")

$(this).parent().closest('div').attr("class")