Reputation: 1
I'm trying to grab all tags within a div called "states", and then uncheck them (they are all checkboxes).
document.getElementById("states").getElementsByTagName("input").checked = false;
For some reason it's not working, though it DOES work if I give them each IDs and use this code for each:
document.getElementById("checkboxName").checked = false;
Any thoughts?
Upvotes: 0
Views: 545
Reputation: 18292
getElementsByName() returns a NodeList. A NodeList does not have a 'checked' property, is a collection of Nodes. What you're trying to do would be very easy with jQuery. But you cand do it your way, just enumerate the NodeList with a for loop (NodeList is Array-like) and change the checked property.
var checkboxes = document.getElementById("states").getElementsByTagName("input");
for (var i = 0; i < checkboxes.length; i++) checkboxes[i].checked = false;
With jQuery:
$('#states input[type="checkbox"]').prop('checked', false);
check it here
Upvotes: 1
Reputation: 2418
getElementsByTagName returns a NodeList. On it you can just do a simple for loop and set checked for each element. Setting the same id for each one of them is not a correct way of doing this as semantically there shouldn't be more than one element with the same id.
Upvotes: 1