Which method is effective?
I have over 500 buttons per page.
<button class="btn-x">test</button> JQuery
// #1 $('button[class*="btn-x"]').live('click', function() { }}); // #2 $('.btn-x').live('click', function() { }}); Which call is effective now, calling the class or the [attr *] button directly, I want to know this, because it can cause a problem later when I have more than 500 buttons, but I'm not sure if they affect the same result.
The class selector will be an order of magnitude faster.
At the same time, live() deprecated. You must use delegate() , or if you are using jQuery 1.7+ on () `.
For instance:
// < jQ 1.7 $('#staticParent').delegate('.btn-x', 'click', function() { }); // jQ 1.7+ $('#staticParent').on('click', '.btn-x', function() { }); If you have a class attribute, it makes sense to use a class selector above the attribute selector. Efficiency is provided as an added bonus; both jQuery and native browser versions have special optimizations for class selectors due to their related semantics and usage.
In addition, this is not the right way to handle class attributes using attribute selectors. You probably mean [class~="btn-x"] , not [class*="btn-x"] . Each of these matches assigns attribute values ββin a different way, with the former behaving more carefully to the selector for the class attribute.
The most efficient is having one event handler instead of 500.
As @Rory McCrossan said, it's best to bind an event handler to a static parent:
// one event handler, recommended $('#staticParent').on('click', '.btn-x', function() { }); // 500 event handlers, not recommended $("button.btn-x").on("click", function() { ... }); If you are looking for the most efficient code you can do:
document.getElementsByClassName("btn-x"); But I think this does not work in IE. If you are looking for a solution suitable for IE, you can do:
function getElementsByClassName(className) { var a = []; if (document.getElementsByClassName) { a = document.getElementsByClassName(className); } else { var node = document.body; var re = new RegExp('(^| )'+classname+'( |$)'); var els = node.getElementsByTagName("*"); for(var i=0,j=els.length; i<j; i++) { if(re.test(els[i].className)) { a.push(els[i]); } } } return a; } (the latter is taken from javascript document.getElementsByClassName compatibility with IE )
I have not tested it, but it should be more efficient than using jQuery.