jQuery select descendants, including the parent

2019-01-26 03:19发布

问题:

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?

回答1:

If I understand you correctly:

$(currentDiv).contents().addBack('.foo').css('color','red');

I renamed the "div" to "currentDiv" for clarity. This selects the current element and all of the elements it contains, then filters out the ones that do not have class foo and applies the style to the remainder, i.e., the ones that do have class foo.

EDIT A slight optimization

$(currentDiv).find('.foo').addBack('.foo').css('color','red');

EDIT

This answer has been updated to incorporate newer jQuery methods. It was originally

$(currentDiv).find('.foo').andSelf().filter('.foo').css('color','red');

which is still required for jQuery older than 1.8



回答2:

jQuery 1.8 introduced .addBack(), which takes a selector, in favor of .andSelf().So tvanfosson's code becomes much more efficient as

$(currentDiv).find(".foo").addBack(".foo").css("color", "red");

If you didn't have that, I think that

$(currentDiv).find(".foo").add(currentDiv.filter(".foo")).css("color", "red");

would be pretty efficient, if not very pretty.



回答3:

Andrew's answer was so useful and the most efficient of all the answers (from jQuery 1.8 onward), so I did as Sam suggested and turned it into a trivial jQuery extension method for everyone to use:

Extension code:

jQuery.fn.findAndSelf = function (selector){
    return this.find(selector).addBack(selector);
};

use like this:

$(function(){
    $('#obj').findAndSelf('.foo').css('color', 'red');
});

JSFiddle: http://jsfiddle.net/BfEwK/

Full credit to Andrew for suggesting addBack() as the best option (as at this date). Have upvoted him accordingly and suggest everyone do the same.



回答4:

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


回答5:

If I am not mistaken could you not just do the following?

$("#obj").css("color", "red").find(".foo").css("color", "red");

Find intended object/element apply CSS, then find all objects/elements within said object/element with said selector and then apply the CSS to is as well?



回答6:

A shorter way to select all descendant elements, including the parent element:

$('*', '#parent').addBack();

Which is the same as:

$('#parent').find('*').addBack();

$('*', '#parent').addBack().css('border', '1px solid #f00');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent">
  <span>Child</span>
  <span>Another child</span>
</div>

Of course, you can change the universal selector to the desired element.

$('.foo', '#parent').addBack();

or

$('#parent').find('.foo').addBack();


回答7:

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

$(document).ready(function(){
    $("div.foo").css("color", "red");
});


回答8:

 $('div.foo, div.foo > *').css('color','red');

The main idea is that you can separate different rules to match on by commas. Just like in css. As far as I know everything here is supoprted by jquery and can be "ORed" by comma-separating.