Best Practice: Select by id or class with jQuery?
Assuming that every element in the DOM has its own unique class name:
Is it better practice to use IDs versus class names when selecting elements in the DOM with jQuery?
开发者_StackOverflowAre 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!
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.
Selecting by ID is still faster than by class-names in jquery.
精彩评论