jQuery select descendants, including the parent jQuery select descendants, including the parent jquery jquery

jQuery select descendants, including the parent


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


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.


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.