无法更改querySelectorAll结果中元素的样式

问题描述

我正在尝试在页面上编辑div的样式以将其隐藏。我能够做到这样

  let mainPanelFirstChild = document.getElementById("jp-main-content-panel")
    .children[0];
  (mainPanelFirstChild as HTMLElement).style.display = "none";

具有具有id属性的元素,但是我要隐藏的元素没有id属性

以下是无法正常运行的代码

    const closeIconNodeList = document.querySelectorAll(
      ".p-TabBar-tabCloseIcon"
    );
    closeIconNodeList.forEach((node) => {
      console.log(node);
      (node as HTMLElement).style.display = "none";
    });

console.log显示了我期望的元素,但是更改style.display属性没有任何作用。我尝试使用典型的for循环遍历document.querySelectorAll来直接处理元素。也没做。

解决方法

我已使用您的一些代码来创建您可能要完成的工作的摘要。

编辑:更新了代码段以改为使用循环

//if you choose to use querySelectorAll then you must either target a specific element or loop through the available elements that you want to target with class ".p-TabBar-tabCloseIcon"

//if you are only targeting one element then use document.querySelector instead

//here we will use querySelectorAll like in your example
var closeIconNodeList = document.querySelectorAll(".p-TabBar-tabCloseIcon");

//below I have created a loop to check the amount of elements in the array that is output using querySelectorAll

//the hideMe function will hide all elements in the array that use class "p-Tabbar-tabCloseIcon" 
const hideMe = function() {
for (var x = 0; x < closeIconNodeList.length; x++)
    closeIconNodeList[x].style.display = 'none';
 };
<div class="p-TabBar-tabCloseIcon">Hide me</div>
<div class="p-TabBar-tabCloseIcon">Hide me 2</div>
<div class="p-TabBar-tabCloseIcon">Hide me 3</div>
<button onclick="hideMe();">Click To Hide</button>

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...