javascript getElementsByClassName() 总是不返回?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5179798/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript getElementsByClassName() always returns none?
提问by matt
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.
我的身体中有多个 div.source 。默认情况下,它们设置为.source { display:none; }
使用 css。
My console tells me: Uncaught TypeError: Cannot set property 'display' of undefined
我的控制台告诉我: 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?
当我单击书签时,所有 .source div 都应该可见。我在这里做错了什么?
回答by erickb
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.
而且正如@ionoy 提到的,使用display
属性。我希望这有帮助。
回答by ionoy
There is 'visibility' and there is 'display'. They are quite different beasts.
有“可见性”和“显示”。他们是完全不同的野兽。
W3Schools:
W3学校:
回答by Dinesh
Go for display
. It's works fine with many browsers and in many cases.
去吧display
。它在许多浏览器和许多情况下都可以正常工作。