How to switch a getElementById to getElementsByClassName [duplicate]
Im trying to switch a getElementById to getElementsByClassName
for a project like this: http://jsfiddle.net/2waZ2/21/
My simple efforts just 开发者_Go百科dont work: http://jsfiddle.net/2waZ2/27/
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/
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/
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)
精彩评论