-1

Possible Duplicate:
getElementByClass().setAttribute doesn't work

Why this:

document.getElementsByClassName('cke_source').setAttribute('name', "mymessage") 

Is returning:

TypeError: Object #<NodeList> has no method 'setAttribute'

document.getElementsByClassName('cke_source') is returning the object correctly.

  • No jQuery please.
Community
  • 1
  • 1
Adam
  • 2,948
  • 10
  • 43
  • 74
  • 2
    `console.log(document.getElementsByClassName('cke_source'));` PS: according to the error message you get `NodeList`, not a node – zerkms Jun 25 '12 at 20:46

2 Answers2

5

document.getElementsByClassName will return a node list (like an array) of elements. So, you need to treat it like an array. Try this if you only have one element:

document.getElementsByClassName('cke_source')[0].setAttribute('name', "mymessage")
Will
  • 19,661
  • 7
  • 47
  • 48
5

getElementsByClassName is giving you back a collection of items, not a single item.

var pColl = document.getElementsByClassName('cke_source');
for (var ii=0; ii< pColl.length; ii++)
{
    pColl[ii].setAttribute('name', 'foo');
}
John Green
  • 13,241
  • 3
  • 29
  • 51
  • 1
    Just out of curiousty. Why `ii` and not `i` as variable ? Is it a convention anywhere or anything in particular ? – Jashwant Jun 25 '12 at 20:53
  • 1
    It is a convention that a lot of people use. The thinking is that when you need to trace through code... doing a search for 'i' is pretty useless. : ) – John Green Jun 25 '12 at 22:52
  • Thanks! Just what I wanted –  Dec 23 '13 at 09:59