Is there an immediate equivalent in javascript for the below jquery code?
$('.checkbox').each(function() {
if ($(this).is(':checked')) {
//logic here
}
});
I’m trying to run through all the checkboxes on a page with class = 'checkbox' – the client doesn’t want to use jQuery, so I need an alternative for the above.
I’m hoping I can avoid writing a long function from scratch to do this and simply use something built-in to JavaScript, but it’s looking like it’s not possible.
Many older browsers don’t support
querySelectorAllorgetElementsByClassName, so you’d have to loop over all<input>elements in those browsers. It’s always best to check for those functions first, though.Secondly, you should never use
$(this).is(":checked")— not even in jQuery — it’s a very slow path to take when looking forthis.checked.This should get you going:
In the example above, you can change the value of
baseto any element. This means that, if all these elements have a common parent or ancestor node, you can set that element as the base and it should run faster, e.g: