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

标签 javascript jquery css-selectors

var classes = $(this).attr('class').split(' '); // this gets the current element classes

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

上述情况的parent是ankor。

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

var classes = $(this).div:parent().attr('class').split(' '); // just a quick try.

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

谢谢

最佳答案

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

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

关于javascript - 如何使用 jQuery 选择第一个父 DIV?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7089229/

相关文章:

javascript - AngularJs:从另一个指令内的指令调用 Controller 方法

javascript - 无法将 JSON 文件放入变量中

jquery - 使用 icheck 选择所有复选框

jQuery 洪水填充算法

CSS 选择器 :not(. ..) [parent 有一些类]

javascript - 新代理(新 map (),{})。值

javascript - jquery多次运行时缓存元素一次

javascript - 在滚动事件上设置滚动顶部动画

html - 如何通过 xlink :href attribute with CSS? 选择 XML 元素

html - CSS 不是最后一个 child - 无法删除最后一个分组的边框