0

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?

László Csiki
  • 125
  • 3
  • 14

3 Answers3

3

The getElementsByName() returns a nodelist collection with a given name in the document. So you should access first element, by doing

checkbox[0].setAttributeNode(att);
Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162
3

document.getElementsByName(value); returns a node list instead of just a single node. You should loop over the list and use setAttributeNode() on each of the nodes in the list.

Luuuud
  • 4,206
  • 2
  • 25
  • 34
2

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

br3t
  • 1,646
  • 2
  • 20
  • 27