问题
有一个div标签,通过class拿到该标签后,想隐藏块的内容。
document.getElementsByClassName("xxx").style.display = "none";
这样写结果发现不生效。
分析
在浏览器里调试了一下,找到这个div,添加display: none可以隐藏该块的内容。这说明不是display: none的问题。
在console里面打印 document.getElementsByClassName("xxx").style.display
,提示:
Uncaught TypeError: Cannot read properties of undefined (reading 'display') at <anonymous>:1:68 (anonymous) @ VM7808:1
提示很明确,没有display这个属性。
在console里面输出 document.getElementsByClassName("xxx")
, 输出了一个
HTMLCollection [div.xxx]0: div.xxxlength: 1[[Prototype]]: HTMLCollectionitem: ƒ item()length: (...)namedItem: ƒ namedItem()remove: ƒ ()constructor: ƒ HTMLCollection()Symbol(Symbol.iterator): ƒ values()Symbol(Symbol.toStringTag): "HTMLCollection"get length: ƒ length()[[Prototype]]: Object
解决
document.getElementsByClassName("xxx")[0].style.display = "none";
通过document.getElementsByClassName(“xxx”) 获取到的是一个HTMLCollection
这看起来像是一个数组,里面有两个元素,第一个元素是一个div,第二个元素是一些Prototype的HTMLCollection。
所以这样获取到之后取出元素0就拿到了该div,再去设置display: none 就不会有问题了。