How can I get jQuery $('.class', context) to include context itself if it matches .class?

jquery, jquery-selectors

Solution

You can do this:

$(context).find('*').andSelf().filter(filters)

.andSelf() appends the previous element on the stack, in this case the context. But...I'm not sure this is really any better than your current approach, with the filtering it's a bit slower. I think you've just hit a situation that doesn't look pretty, would be nice if `.andSelf()` took a selector, then you could do:

$(context).find(filters).andSelf(filters)

Still not a huge improvement though.

Problem

I want to be able to match against all elements in a given context including the context element itself. Here is the code I'm using currently, but it seems inefficient. Is there a better way? Note: I'm using jQ 1.3.2, but I'll upgrade soon so I'm interested in 1.4 solutions too. ``` var context = $('#id'); var filters = '.class1, .class2'; // take context itself if it matches filters $(context).filter(filters) // add anything matching filters inside context .add($(filters, context)) ``` Note: `.add($(f,c))` works in jQ 1.3 as `.add(f,c)` in jQ 1.4

Original source