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?
jQuery 1.8 introduced .addBack(), which takes a selector, in favor of .andSelf().So tvanfosson's code becomes much more efficient as
If you didn't have that, I think that
would be pretty efficient, if not very pretty.
A shorter way to select all descendant elements, including the parent element:
Which is the same as:
Of course, you can change the universal selector to the desired element.
or
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.
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:
use like this:
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.If I am not mistaken could you not just do the following?
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?
If I understand you correctly:
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 classfoo
.EDIT A slight optimization
EDIT
This answer has been updated to incorporate newer jQuery methods. It was originally
which is still required for jQuery older than 1.8