anmarti
anmarti

Reputation: 5143

More efficient way to get the ONLY element with a certain css class?

I have a menu with several linkbuttons <a class="selected">. When I click on one I apply a class selected, when I click to another one I have to remove its class and assing this class to the new clicked linkbutton.

Therefore there are only one element with a certain class name at the same time and I want to select it in order to remove this class.

I know:

$('.myclass').removeClass('myclass');

I think is not efficient because it has to check all elements of DOM

Which is the more efficient way to get this element: <a class="selected"> and remove its class selected?

Upvotes: 1

Views: 99

Answers (2)

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382274

No, it doesn't check all elements : it uses the optimized getElementsByClassName function.

So looking for elements by their classes, even if not as fast than looking by id, is fast enough, both using jQuery or Vanilla JS.

This being said, as there is only one element (and supposing your element doesn't have other classes), you can avoid the parsing made by jQuery if it's really so important for you to make it faster :

document.getElementsByClassName('myclass')[0].className = '';

For people wanting to see the code, this is one of the possible "speed-ups" in jQuery searches for element :

// Speed-up: Sizzle(".CLASS")
} else if ( (m = match[3]) && assertUsableClassName && context.getElementsByClassName ) {
    push.apply( results, slice.call(context.getElementsByClassName( m ), 0) );
    return results;
}

Upvotes: 7

Anthony Grist
Anthony Grist

Reputation: 38345

There isn't a more efficient way to do that; if it only has a class, and not an ID that you could store, then your best option is the class selector.

Upvotes: 0

Related Questions