My ultimate goal here is to get a list of radiobuttons and check/uncheck them. Here is my code:
for (var radio in document.getElementsByTagName('input')) {
if(typeof (radio) != "string")
alert(radio);
}
The alert
never gets called.
The call to document.getElementsByTagName returns a list of strings numbered from 0 to the leng开发者_如何学Cth of the list, so all of their properties (type, id, etc) are undefined and I can't really do much with them.
Am I doing something wrong here? Why aren't objects being returned for these elements?
This is in firefox 4 and chrome, if that helps.
getElementsByTagName
returns a NodeList
object, which is Array
-like in the sense that it prototypes arbitrary numeric indices onto it.
You should not use a for..in
loop to enumerate through a NodeList
.
Why?
Because for..in
iterates through all of the properties of an object, which will cause extra unwanted properties that exist in NodeList
as well as the arbitrary indices prototyped
onto it (which, by the way are properties too.)
Since you are iterating through the indices, you are guaranteed not to get any object other than a DOMElement
object. Therefore, you do not need the typeof
check.
So, I think you meant to do this:
var els = document.getElementsByTagName('input');
for(var i = 0, j = els.length; i < j; i++) {
alert(els[i]);
}
Or, you can also do this, but I don't recommend it:
var els = document.getElementsByTagName('input');
for(var index in els) {
if(els.hasOwnProperty(index) && typeof index === 'number') {
//we have an element
alert(els[index]);
}
}
Try using a normal for loop. for ( x in obj ) loops over the properties of the object, not the actual elements of the array.
var els = document.getElementsByTagName("input");
for ( var i=0; i<els.length; i++ ) {
var radio = els[i];
if ( typeof(radio) != "string" ) {
alert(radio);
}
}
Live Demo
As others have stated, getElementsByTagName
returns a NodeList
object and you need to iterate through it differently. Here are some ways to accomplish your ultimate goal of checking/unchecking the radios.
With jQuery
$.each($('input[type="radio"]'), function () {
if (true) // Your condition for checking true
$(this).attr('checked','checked');
else
$(this).removeAttr('checked');
});
Without jQuery
var inputs = document.getElementsByTagName('input');
for(var i = 0; i < inputs.length; i++){
var input = inputs.item(i);
if(input.type == "radio")
if (true) // Your condition for checking true
input.checked = "checked";
else
input.removeAttribute("checked");
}
}
精彩评论