javascript getElementsByClassName() always returns none?

限于喜欢 提交于 2019-12-17 19:43:00

问题


hey guys, i wanna 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?


回答1:


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/




回答2:


There is 'visibility' and there is 'display'. They are quite different beasts.

W3Schools:

visibility

display




回答3:


Go for display. It's works fine with many browsers and in many cases.



来源:https://stackoverflow.com/questions/5179798/javascript-getelementsbyclassname-always-returns-none

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!