考虑以下 HTML:
<div class="foo" id="obj">
I should be changed red
<div class="bar" style="color:black;">
I should not be changed red.
<div class="foo">I should be changed red.</div>
</div>
</div>
给定一个 DOM 元素obj
和一个表达式,我该如何选择任何子元素和可能obj
?我正在寻找类似于“选择后代”但也包括父母的东西,如果它与表达式匹配。
var obj = $("#obj")[0];
//wrong, may include siblings of 'obj'
$(".foo", $(obj).parent()).css("color", "red");
//wrong -- excludes 'obj'
$(".foo", obj).css("color", "red");
//correct way, but it's annoying
var matches = $(".foo", obj);
if ($(obj).is(".foo")) matches = matches.add(obj);
matches.css("color", "red");
有没有更优雅的解决方案?