dom - Best Practice: Select by id or class with jQuery? -


Below each element of the dome has its unique class name:

  1. < P> Is it better practice to use name names versus class names when selecting elements in DOM with jQuery?
  2. What is the benefit when using one on the other in jQuery?

    I have been told that getting a DOM element through ID instead of class is very fast and generally better practice, but is it also applicable to jQuery it happens?

    jQuery simply takes advantage of browser functionality Old browsers (IE & lt ; 9), there is no getElementsByClassName function, but almost every browser supports getElementById . On these browsers, jQuery has to cross the whole tree and find all the elements with the given classname. Therefore, the use of the ID will be faster.

    However, keep in mind that the ID must be unique, i.e. you can not have two elements with the same ID. This is not often advised, because components can be used in different contexts on the same page. Use of IDs in particular must be stopped.

Comments