元素相对的CSS选择器

时间:2015-06-17 10:02:49

标签: javascript jquery css-selectors selectors-api

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

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

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

基本上是这样:"给我直接父母/子女(如果有的话)"

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

更新:

closest('table)不起作用:可以返回元素本身并且可能找不到直接父母 find('td')不起作用:因为我只需要直接的孩子;在下面的子树中可能有很多这些

3 个答案:

答案 0 :(得分:3)

您可以使用closest获取最接近的ancestor

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

对于集合中的每个元素,通过测试元素本身并遍历DOM树中的祖先来获取与选择器匹配的第一个元素。

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

find搜索DOM树:

  

获取当前匹配元素集中每个元素的后代,由选择器,jQuery对象或元素过滤。

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

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

答案 1 :(得分:1)

您可以使用.closest()查找计算给定选择器的第一个祖先

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

在下面的案例中,将find()child selector

一起使用
element.children('tbody').children('tr').children('td') -> element.find('> tbody > tr > td')

答案 2 :(得分:0)

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

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