首页 > 解决方案 > 无法使用 getElementById() 获取应用了“显示:无”属性的元素

问题描述

我遇到了一个问题,即该getElementById()函数无法在页面上获取display: none应用了该属性的特定元素,即使它在 DOM 中可见(我可以看到 div 及其 id 存在于最终呈现的页)。

有没有解决的办法?

这是代码:

    togglePanel() {
        const panelId = this.accordionItem.querySelector("#collapsible-panel");

        this.shouldShowAccordion = !this.shouldShowAccordion;

        if (this.shouldShowAccordion) {
            panelId.classList.remove("collapsed");
        }
        else {
            panelId.classList.add("collapsed");
        }  
    }

“collapsible-panel”是display: none应用到它的 div 的 ID。

标签: javascriptgetelementbyidqueryselector

解决方案


setTimeout(() => {
  document.querySelector("div[id='collapsiblepanel']").style.display = 'block';

}, 2000)
#collapsiblepanel {
  width: 200px;
  height: 100px;
  background-color: red;
  display: none;
}

Following is ana example where I am selecting a div which has the value of display as none. After 2 seconds I am setting up it's display to block.
<div id="collapsiblepanel">

</div>


推荐阅读