jQuery select descendants, including the parent

2019-01-26 03:24发布

Consider the following 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>

Given a DOM element obj and an expression, how do I go about selecting any children and possibly obj? I'm looking for something similar to "select descendants" but also including the parent, if it matches the expression.

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");

Is there a more elegant solution to this?

8条回答
爷、活的狠高调
2楼-- · 2019-01-26 04:05

Barring a nicer solution, I've created a new function and use it instead of $:

var _$ = function(expr, parent){ 
   return $(parent).is(expr) ? $(expr, parent).add(parent) : $(expr, parent); 
}
查看更多
贪生不怕死
3楼-- · 2019-01-26 04:05

Doesn't this do what you want (unless I misunderstand...)

$(document).ready(function(){
    $("div.foo").css("color", "red");
});
查看更多
登录 后发表回答