jQuery makes selecting DOM elements using classes as easy as selecting elements by ID used to be, so it’s tempting to use classes much more liberally than before. It’s still much better to select by ID though because jQuery uses the browser’s native method (getElementByID) to do this and doesn’t have to do any of it’s own DOM traversal, which is much faster. How much faster? Let’s find out.
I’ll use the previous example and adapt it so each LI we create has a unique class added to it. Then I’ll loop through and select each one once.
// Create our list var list = $('.list'); var listItems = '<ul>'; for (i = 0; i < 1000; i++) { listItems += '<li class="listItem' + i + '">This is a list item</li>'; } listItems += '</ul>'; list.html(listItems); // Select each item once for (i = 0; i < 1000; i++) { var selectedItem = $('.listItem' + i); }
Just as I thought my browser had hung, it finished, in 5066 milliseconds (about 5 seconds). So, I modified the code to give each item an ID instead of a class and then selected them using the ID.
// Create our list var list = $('.list'); var listItems = '<ul>'; for (i = 0; i < 1000; i++) { listItems += '<li id="listItem' + i + '">This is a list item</li>'; } listItems += '</ul>'; list.html(listItems); // Select each item once for (i = 0; i < 1000; i++) { var selectedItem = $('#listItem' + i); }
This time it only took 61 milliseconds. Nearly 100x faster.