问题描述
我正在尝试在页面上编辑div的样式以将其隐藏。我能够做到这样
let mainPanelFirstChild = document.getElementById("jp-main-content-panel")
.children[0];
(mainPanelFirstChild as HTMLElement).style.display = "none";
以下是无法正常运行的代码:
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>