Javascript jQuery-如果子级包含类,则将类添加到父级

Javascript jQuery-如果子级包含类,则将类添加到父级,javascript,jquery,Javascript,Jquery,我试图将一个类添加到父DIV中,如果它有一个子IMG元素,其类为“testing” 用于选择父元素 $("article img.testing").parent().addClass('hasclass'); $(“article img.testing”).parent().addClass('hasclass') .hassclass{ 背景:红色; } 根据您对@Tushar答案的评论,为了帮助详细说明如何遍历多个父节点,我通常采用以下方法: 要将类添加到直接父级div: $('ar

我试图将一个类添加到父DIV中,如果它有一个子IMG元素,其类为“testing”

用于选择父元素

$("article img.testing").parent().addClass('hasclass');
$(“article img.testing”).parent().addClass('hasclass')
.hassclass{
背景:红色;
}

根据您对@Tushar答案的评论,为了帮助详细说明如何遍历多个父节点,我通常采用以下方法:

要将类添加到直接父级
div

$('article img.testing').parent().toggleClass('new-class', true);
并将该类添加到包含的
文章中
父类:

$('article img.testing').parents('article:first').toggleClass('new-class', true);
我还喜欢使用看起来“更干净”的方法来避免将同一个类两次添加到元素中的任何机会,尽管我相信jQuery会检查这一点


希望这有帮助

像这样尝试
$(this).parent().addClass()
,但是需要double.parent将类添加到文章$(“article”)。查找(“.testing”).parent().parent().addClass('hasclass');
$('div:has(img.testing)').addClass('hasclass');
$('article img.testing').parent().toggleClass('new-class', true);
$('article img.testing').parents('article:first').toggleClass('new-class', true);