1

Im trying to switch a getElementById to getElementsByClassName

for a project like this: http://jsfiddle.net/2waZ2/21/

My simple efforts just dont work: http://jsfiddle.net/2waZ2/27/

Jon
  • 6,437
  • 8
  • 43
  • 63

3 Answers3

3

Change

document.getElementsByClassName('mytable').appendChild( row ) ; 

to

document.getElementsByClassName('mytable')[0].appendChild( row ) ; 

http://jsfiddle.net/2waZ2/30

and also remove dot in your class name.

Or easily use jQuery

row = displayArrayAsTable(QR4, 24, 25);
$(".mytable").append(row); 

http://jsfiddle.net/2waZ2/32/

genesis
  • 50,477
  • 20
  • 96
  • 125
  • Thats sweet - what dies the [0] mean? I tried with and without the .class and I saw someone using it so I thought maybe... – Jon Sep 21 '11 at 12:32
  • 1
    @Jon edited. getElementsByClassName gives an array instead of selected element – genesis Sep 21 '11 at 12:33
  • @Jon dot is used in jquery and also in CSS – genesis Sep 21 '11 at 12:33
  • @Jon `getElementsByClassName` returns an array of elements (hence "elements"). To get the first item of an array, you use `[0]`. – Skilldrick Sep 21 '11 at 12:35
  • an array of classes - brilliant. That has allowed me to do some cool stuff. Thanks for the help. Great answer - dont know why my q was marked down! – Jon Sep 21 '11 at 12:37
0

Almost there, you just need to remove the dot in getElementsByClassName and only get the first result from that, like this:

document.getElementsByClassName('mytable')[0]

http://jsfiddle.net/2waZ2/33/

Jayne Mast
  • 1,427
  • 1
  • 16
  • 32
0

getElementsByClassName returns array of elements, not single element, as getElementById. So you should iterate over your collection (unless you want to append only to first found element) with:

var elements = document.getElementsByClassName('mytable');
for(var i = 0; i < elements.length; i++) { elements[i].appendChild( row ) }; 

Also remove dot from class name, as it's not part of class name (the same as # is not part of id)

MBO
  • 30,379
  • 5
  • 50
  • 52