test JQuery // #1 $('button[class*="btn-x"]')....">

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.

+4
source share
5 answers

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() { }); 
+9
source

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.

+4
source

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() { ... }); 
+2
source

The class selector is faster. The class selector only works slower than the id selector. And you should use .delegate() or .on() for jQuery 1.7 and later) instead of .live() . In your case, this is important because .delegate() attaches one handler instead of 500 for .live() .

+1
source

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.

0
source

All Articles