user2015253
user2015253

Reputation: 1444

Should I check if an element hasClass() before I removeClass()?

If I definitely want to remove a certain class from an element, should I blindly call removeClass() or should I check with hasClass() first?

Is there any mentionable performance advantage in either of these methods? Is there a best practice for this?

Example:

function showMessage(){
    $('.message').removeClass('hidden');
}

vs.

function showMessage(){
    if($('.message').hasClass('hidden')){
        $('.message').removeClass('hidden');
    }
}

Upvotes: 3

Views: 653

Answers (1)

Robby Cornelissen
Robby Cornelissen

Reputation: 97282

The call to removeClass() doesn't throw any errors if the class is not present on the element(s), so there really is no need to call hasClass() first. It just causes additional overhead.

When asking about performance though, the calls to getClass() and removeClass() are likely to be fast. It's the repeated lookup of the .message elements in the DOM that will slow things down. So, in case you want to call hasClass() first, it's better not to repeat the element lookup:

function showMessage() {
    const message = $('.message');

    if(message.hasClass('hidden')){
        message.removeClass('hidden');
    }
}

Upvotes: 8

Related Questions