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

I want to be able to map all elements in a given context, including the context element itself.
Here is the code I'm currently using, but it seems to be inefficient. Is there a better way?
Note. I am using jQ 1.3.2, but I will be updating soon, so I am also interested in 1.4 solutions.

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

+4
source share
2 answers

You can do it:

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

. andSelf () pushes the previous item onto the stack, in this case context. But ... I'm not sure if this is really better than your current approach, and it is a bit slower. I think that you just got into a situation that doesn’t look very nice, it would be nice if .andSelf() took a selector, then you could do:

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

However, this is not a big improvement.

+3
source

It seems that the @Nick Craver idea went into production. jQuery The addBack () function has replaced andSelf() and accepts a selector.

 $(context).find(filters).addBack(filters) 
+2
source

Source: https://habr.com/ru/post/1304503/


All Articles