开发者

How to switch a getElementById to getElementsByClassName [duplicate]

This question already has answers here: What do querySelectorAll and getElementsBy* methods return? (12 answers) Closed 7 years ago.

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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜