元素相关 CSS 选择器

Element-relative CSS selectors

有没有办法通过使用 CSS 选择器和 jQuery 来缩短这些类型的行?

$(element).parent('tr').parent('tbody').parent('table')

$(element).children('tbody').children('tr').children('td')

基本上是:"get me the direct parent/children if any"

我需要 100% 相等的选择器。

更新:

closest('table) 不起作用:return 元素本身可以找到不直接的父元素 find('td') 不起作用:因为我只需要直系子代;下面的子树中可能有很多

您可以使用 closest 得到最接近的 ancestor:

element.closest('table') // element.parent('tr').parent('tbody').parent('table')

For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

文档:http://api.jquery.com/closest/

find 向下搜索 DOM 树:

Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.

element.find('td') // element.children('tbody').children('tr').children('td')

文档:http://api.jquery.com/find/

您可以使用 .closest() 找到匹配给定选择器的第一个祖先

element.parent('tr').parent('tbody').parent('table') -> $(element).parent('tr').closest('table')

在下面的例子中使用find() with child selector

element.children('tbody').children('tr').children('td') -> element.find('> tbody > tr > td')

使用closest向上移动到最接近的匹配元素。此外,使用 find 搜索给定元素(请注意,查找将获取所有匹配元素,直至所有现有的 DOM 树层)

element.closest('table');
element.find('td');