J-Kablamo
J-Kablamo

Reputation: 1

getElementsByTagName within a getElementByID

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

Answers (2)

Oscar Paz
Oscar Paz

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

Vasil Dininski
Vasil Dininski

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

Related Questions