Skip to content Skip to sidebar Skip to footer

Best Practices For Writing Jquery Selectors

I'm currently writing very explicit selectors in my jQuery code. For example given this markup

Solution 1:

Actually, since IDs are unique you can simply select on the ID from the start.

var $select = $('#codeChoice');

As far as your other question goes, there is no easy answer. Multiple selectors can cause slowdowns, but you really have to try to know. Furthermore, it depends on the browser. Your best bet for checking it out is using http://jsperf.com/

Also, as is noted in this, you should make sure to place the less specific selector on the left, like this:

var $codeBlue = $('.codeblue #codeChoice');

Solution 2:

If you use concrete IDs, jQuery will be faster because it uses the native method document.getElementById(); As your first selector includes 4 Classes ( = Slow Detection ) and 1 id (= Faster Detection) and your second selector 1 Class ( = Slow Detection) and 1 Id ( = Faster Detection) , the second will be faster.

Generally selectors will be faster as less pieces are included.

Solution 3:

var $select = $("#codeChoice"); 

should be enough, as the id should be unique

Solution 4:

The fastest way to select an element in jQuery is by ID. Accessing element by Id is good for performance. As the id is unique on the page.

High performance Javascript book

var$select = $('#codeChoice");

Post a Comment for "Best Practices For Writing Jquery Selectors"