javascript getElementsByClassName() 总是不返回任何内容?
我想为我的浏览器创建最简单的书签。
javascript:document.getElementsByClassName('source').style.visibility='visible';
我体内有多个 div.source 。默认情况下,它们设置为 .source { display:none; }
与 CSS。
我的控制台告诉我:Uncaught TypeError: Cannot set property 'display' of undefined
当我单击书签时,所有 .source div 都应该可见。我在这里做错了什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可能需要循环遍历结果,如下所示:
并且正如 @ionoy 提到的,使用
display
属性。我希望这有帮助。http://jsfiddle.net/erick/rb7bn/1/
You might need to loop through the results, like this:
And also as @ionoy mentioned, use
display
attribute. I hope that helps.http://jsfiddle.net/erick/rb7bn/1/
有“可见性”,也有“显示”。它们是完全不同的野兽。
W3Schools:
可见性
显示
There is 'visibility' and there is 'display'. They are quite different beasts.
W3Schools:
visibility
display
选择
显示
。它在许多浏览器和许多情况下都可以正常工作。Go for
display
. It's works fine with many browsers and in many cases.永远不要迭代实时 HTML 集合。它的效率极低,因为每次访问实时集合的成员(包括长度)时,浏览器都会遍历整个文档以查找特定元素。请参阅此处。
这是 efficeint 解决方案:
使用
[...HTMLcollection]
perfix 将 HTMLcollection 转换为数组,然后您可以迭代它。Never itarate live HTML collection. it is extremly inefficient as every time you access a member of a live collection (including the length), the browser traverses the entire document to find the specific element. see here.
Here is the efficeint solution:
using
[...HTMLcollection]
perfix converts the HTMLcollection to an array, then you can itarate it.