Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery select descendants, including the parent

Tags:

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?

like image 954
Sam Avatar asked Dec 13 '08 03:12

Sam


People also ask

What is descendants in jQuery?

With jQuery you can traverse down the DOM tree to find descendants of an element. A descendant is a child, grandchild, great-grandchild, and so on.

How can we select descendants of an element?

A descendant selector is made up of two or more selectors separated by white space. A descendant selector of the form " A B " matches when an element B is an arbitrary descendant of some ancestor element A .

What is parent () parent () jQuery?

The parent() method returns the direct parent element of the selected element. The DOM tree: This method only traverse a single level up the DOM tree. To traverse all the way up to the document's root element (to return grandparents or other ancestors), use the parents() or the parentsUntil() method.

Which of the following selectors would be considered a descendant selector in jQuery?

The ("parent descendant") selector selects all elements that are descendants of a specified element.


1 Answers

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

like image 81
tvanfosson Avatar answered Oct 13 '22 00:10

tvanfosson