Many older browsers do not support querySelectorAll
or getElementsByClassName
, so you will have to querySelectorAll
over all the <input>
elements in these browsers. However, it is always better to test these features.
Secondly, you should never use $(this).is(":checked")
- not even in jQuery - this is a very slow way to find this.checked
.
This should make you:
var base = document, inps, tmp, i = 0, reg = /\bcheckbox\b/; // getElementsByClassName is the fastest method if (base.getElementsByClassName) inps = base.getElementsByClassName("checkbox"); // Followed by querySelectorAll else if (base.querySelectorAll) inps = base.querySelectorAll(".checkbox"); // But if neither exist, loop through all the elements and check the class else { inps = []; var tmp = base.getElementsByTagName("input"); i = tmp.length; while (i--) { if (reg.test(tmp[i].className) inps.push(tmp[i]); } } // Finally, loop through the matched elements and apply your logic i = inps.length; while (i--) { var current = inps[i]; if (current.checked) { // logic here } }
In the above example, you can change the base
value to any element. This means that if all these elements have a common parent or ancestor node, you can set this element as a base, and it should work faster, for example:
var base = document.getElementById("myForm");
source share