joshmoto joshmoto - 2 months ago 7
jQuery Question

fastest way to check if possible array of classes exist in an element using jquery

I'm looking for the best way to tidy this up, or the actual fastest and best way to execute such method.

I've read plenty of questions on stackoverflow and cant work this one out. I have a working solution below, but it seems bloated and there maybe a faster or more cleaner approach to this.

See test fiddle here.

I am trying to run a function but only if an array of classes don't exist in my body tag.

See working code below...

// run scroll reveal if none of these ie classes exist in the body tag
if (!$('BODY.ie-9,BODY.ie-8,BODY.ie-7,BODY.ie-6')[0]) {

// scroll reveal function
window.sr = new ScrollReveal({ reset: false });
sr.reveal('FIGURE', { duration: 300 });

}


The only way it seems that i could get the result I wanted want was by having to list
BODY.ie-9,BODY.ie-8,BODY.ie-7,BODY.ie-6
as the a selector.

The result I want is to run the child function if none of these
.ie-
classes exist in the body tag.

Any suggestions would be much appreciated. Thanks

Answer

You don't even need jQuery:

// run scroll reveal if none of these ie classes exist in the body tag
if (!/(?:^|\s)ie\-[6-9](?:$|\s)/.test(document.body.className)) {
    // ...
}

This solution simply checks the class attribute on <body> and tests for whether a class name matches ie-{character between 6 and 9, inclusive} using Regex. It also makes sure that it matches a whole class name (padded by whitespace or by the beginning / ending of the string).