javascript getElementsByClassName() 总是不返回任何内容?

发布于 2024-10-19 23:46:14 字数 353 浏览 6 评论 0原文

我想为我的浏览器创建最简单的书签。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

他不在意 2024-10-26 23:46:14

您可能需要循环遍历结果,如下所示:

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

并且正如 @ionoy 提到的,使用 display 属性。我希望这有帮助。

http://jsfiddle.net/erick/rb7bn/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/

一世旳自豪 2024-10-26 23:46:14

有“可见性”,也有“显示”。它们是完全不同的野兽。

W3Schools:

可见性

显示

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

W3Schools:

visibility

display

☆獨立☆ 2024-10-26 23:46:14

选择显示。它在许多浏览器和许多情况下都可以正常工作。

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

半衬遮猫 2024-10-26 23:46:14

永远不要迭代实时 HTML 集合。它的效率极低,因为每次访问实时集合的成员(包括长度)时,浏览器都会遍历整个文档以查找特定元素。请参阅此处

这是 efficeint 解决方案:

let divs = [...document.getElementsByClassName('source')];
divs.forEach(divEl => {
  divEl.style.display='block'
}

使用 [...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:

let divs = [...document.getElementsByClassName('source')];
divs.forEach(divEl => {
  divEl.style.display='block'
}

using [...HTMLcollection] perfix converts the HTMLcollection to an array, then you can itarate it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文