K. Jackob K. Jackob - 2 months ago 7
Javascript Question

JQuery - Is() function optimalization

I have many iterations where I want to check if myObject have .example class.
I can do this with templateObject that is predefined during initialization as $('.class'):

if(myObject.Is( templateObject )
{
//Do stuff
}


Alternatively, I can use class name directly:

if(myObject.Is( '.example' )
{
//Do stuff
}


So I want to know if second example makes jQuery search through DOM in every iteration or comparison is made in more optimal way? Which example is better?

Answer

IMO jquery hasClass() is more efficient here, it is made specifically for this purpose.

if (myObject.hasClass('example')){
    // Code
}