Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Practice: Select by id or class with jQuery?

Assuming that every element in the DOM has its own unique class name:

  1. Is it better practice to use IDs versus class names when selecting elements in the DOM with jQuery?

  2. Are there any performance advantages when using one over the other in jQuery?

I've been told that traditionally getting a DOM element via ID instead of by class is much faster and usually better practice, but does that apply to jQuery as well?

Many thanks in advance!

like image 434
DondeEstaMiCulo Avatar asked Mar 28 '11 06:03

DondeEstaMiCulo


1 Answers

jQuery just leverages browser functionality. On older browsers(IE<9), there is no getElementsByClassName function, but virtually every browser supports getElementById. On these browsers, jQuery has to traverse the whole tree and look for all elements with the given classname. Therefore, using IDs will be faster.

However, bear in mind that id's must be unique, i.e. you can't have two elements with the same ID. This is often not advisable, since components may be used in different contexts on the same page. Using IDs exclusively would prevent that.

like image 91
phihag Avatar answered Oct 23 '22 03:10

phihag