jQuery – 按子类选择父级?

如何选择包含子

,如下所示?

 
text

根据您的需要,您可以使用parentsclosest parents

 $("div.test").parents("tr"); // Or $("div.test").closest("tr"); 

(初始选择器可以是与你的div匹配的任何东西,所以".test"也可以。)

如果你在表中有一个表, parents将一直看到树,可能匹配多个tr元素。 closest将停止与它遇到的每个div第一个tr

这是使用closest的示例:

实时复制 | 直播源

HTML:

 
text
text
text

JavaScript的:

 jQuery(function($) { var rows = $("div.test").closest("tr"); display("Matched " + rows.length + " rows:"); rows.each(function() { display("Row '" + this.id + "'"); }); function display(msg) { $("

").html(msg).appendTo(document.body); } });

输出:

 匹配3行:
排'先'
排'秒'
排'第三' 
 $('.test').parent('tr') 

这选择了你想要的。

使用selector:has()如:

 $("tr:has(div.test)"); 

在这里找到jQuery文档:has()Selector

你应该使用

 $('.test').parents('tr'); 

例如:

http://jsfiddle.net/7T9nN/

下面的目标是父类,其子类中包含.test,并在下面的示例中将背景更改为红色…

 $(document).ready(function(){ $('.test').parents('tr').css('background-color', 'red'); }); 

对我来说,当尝试从indesign定位导出的html时,这非常强大。 function强大,因为indesign不会让你标记,但通过这个你可以标记a然后通过这个JQuery。

$('.test').parent().parent();$('.text').parent().closest('tr');