Mr.niceGuy Mr.niceGuy - 1 month ago 9
CSS Question

Javascript What is faster? Multiple OR in IF statements to target css, or one IF with multiple css targets

I have set some code to function if the current page contains one of the following attributes below

if($('body[data-section="chicken"]').length || $('body[data-section="friedchicken"]').length){
(function() {
///...
}
}


Now i could simply do it like:

if($('body[data-section="chicken"],body[data-section="friedchicken"]').length){
(function() {
///...
}
}


Basically, a function to auto scroll down on the targeted pages.
But i'm curious! which one is faster to detect these targets?
and the reason I'm asking because i will be using more than 2 css selectors.

Answer

If speed is a concern, then skip the jQuery layer, address the body element directly, and only query for its data-section attribute once:

var attr = document.body.getAttribute('data-section');
if (attr == 'chicken' || attr == 'friedchicken') {
    // ...
};