Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most efficient way to add remove classes with JavaScript

I am curious if anyone knows which of these is more efficient, I am only concerned with Firefox as a browser and do not need to know that this code doesn't work in IE, etc...

Basically I am showing and hiding DOM elements based on an input field's value, an instant search if you will. I need to show or hide a "nothing found" element if no search results are shown. I am curious if it is cheaper (more efficient) to check if the "nothing found" element is in the proper state before modifying its class attribute, or to just modify the class attribute.

Question: should I remove/add the hidden class every time the function is run, even if there is no change in the element's class attribute?

if (shown_count > 0) {
    element.classList.add('hidden');
}
else {
    element.classList.remove('hidden');
}

or should I check to see if the element needs its class attribute updated before actually updating it?

if (shown_count > 0) {
    if (element.classList.contains('hidden') == false) {
         element.classList.add('hidden');
    }
}
else {
    if (element.classList.contains('hidden')) {
         element.classList.remove('hidden');
    }
}
like image 780
macguru2000 Avatar asked Oct 17 '12 15:10

macguru2000


2 Answers

I think the existence check is already done by the native code, so you do not need to check it again.

So let's take a look at the source code( Note: classList is DOMTokenList object)

String DOMTokenList::addToken(const AtomicString& input, const AtomicString& token)
{
    if (input.isEmpty())
        return token;

    StringBuilder builder;
    builder.append(input);
    if (input[input.length()-1] != ' ')   // <--- check happens here
        builder.append(' ');
    builder.append(token);
    return builder.toString();
}

source comes from the WebKit's WebCore

like image 190
xdazz Avatar answered Nov 17 '22 02:11

xdazz


After running some tests on jsperf the answer is simply that the first option is quicker. Likely due to xdazz's answer, that the classList.add method does the check already.

Here is a link to the performance test: http://jsperf.com/add-remove-class-performanci

like image 2
macguru2000 Avatar answered Nov 17 '22 02:11

macguru2000