Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript getElementsByClassName() always returns none?

I want to create the simplest bookmarklet for my browser.

javascript:document.getElementsByClassName('source').style.visibility='visible';

I have multiple div.source in my body. By default they are set to .source { display:none; } with css.

My console tells me: Uncaught TypeError: Cannot set property 'display' of undefined

When I click the bookmarklet all .source divs should be visible. What am I doing wrong here?

like image 238
matt Avatar asked Mar 03 '11 10:03

matt


1 Answers

You might need to loop through the results, like this:

var divs = document.getElementsByClassName('source');
for(var i=0; i<divs.length; i++) { 
  divs[i].style.display='block'
}

And also as @ionoy mentioned, use display attribute. I hope that helps.

http://jsfiddle.net/erick/rb7bn/1/

like image 124
erickb Avatar answered Nov 04 '22 10:11

erickb