Checking if a selector matches elements marked by a specific class

最后都变了- 提交于 2020-02-07 07:27:52

问题


I have a generic jQuery selector (a string):

var selector = '#files li div';

and the name of a class:

var myClass = 'folder';

I want to check if the selector matches elements having the class stored into myClass. As far as now I used an instance of the selector to invoke the method hasClass():

var match = $(selector).hasClass(myClass);

It works, but I thought it may exist some more efficient jQuery method which allows not to create a jQuery instance to get all the elements matched by the selector.
My worry is the memory used by the instance created only for this check and nothing more, althought it is inside the method of a pseudo-class which does not return/expose any reference to this instance.

Can you suggest something better?

<EDIT>
In the example showed I set the value of myClass to "folder" just to easily represent the problem, but in the app I do not know it in advance, since it is defined by user actions.
</EDIT>


回答1:


hasClass() will return true if any of the matched elements has the specified class; not if all of them do.

You might find the following is more what you want:

var match = $(selector).filter('.' + myClass);

But you could then simplify it to:

var match = $(selector + '.' + myClass);

And you'd then check whether you have any elements left using the .length attribute.

if (match.length) // then some were matched!

In terms of worrying about memory usage... don't. premature optimization is the root of all evil. The memory usage here is tiny. If you want to optimize your program (is there a need at the moment?), look at functions which are called a large number of times, or look within loops that have a large number of iterations, or look at DOM manipulation and see if they can be combined; one jQuery selector isn't going to make any difference to your program's speed in relative terms.




回答2:


Either assign Id for uniqueness or create a class if you want to apply on more than one instance



来源:https://stackoverflow.com/questions/7360452/checking-if-a-selector-matches-elements-marked-by-a-specific-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!