Skip to content Skip to sidebar Skip to footer

How To Switch A Getelementbyid To Getelementsbyclassname

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/

Solution 1:

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/

Solution 2:

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/

Solution 3:

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)

Post a Comment for "How To Switch A Getelementbyid To Getelementsbyclassname"