László Csiki László Csiki - 21 days ago 9
HTML Question

Javascript Uncaught TypeError: checkbox.setAttributeNode is not a function

I got an error and i don't know how to resolve it, pls help :)
The code:

var ls_contextid1=JSON.parse(localStorage.getItem('completedArray')) || [];
for (var i = 0; i < ls_contextid1.length; i++){
var obj = ls_contextid1[i];
for (var key in obj){
var value = obj[key];
var checkbox=document.getElementsByName(value);
doc[i] =value;

var att = document.createAttribute('checked');
att.value = 'checked';

checkbox.setAttributeNode(att);

}
}


}

this is the error message:

Uncaught TypeError: checkbox.setAttributeNode is not a function


Local storage contains the json:

[{"contextid":"470"},{"contextid":"468"},{"contextid":"467"},{"contextid":"463"},{"contextid":"463"},{"contextid":"464"}]


And the HTML code:

<input name="470" type="checkbox" disabled="disabled" style="margin-left:50px;">


Can you help me?

Answer

getElementsByName returns collection, so you need use checkbox[0].setAttributeNode(att);. I also recommend you check element's existing before setting attribute.