我正在嘗試使用javascript選擇要顯示和隱藏的元素,我無法對html進行更改,下面的javascript show error on“Cannot set property'display'of undefined”。如何顯示和隱藏共享同一類的元素?
var showHideBrandPic = document.querySelectorAll("h1.plp_brand_title");
var pic = document.querySelectorAll('.hero_discription_container_left');
function showHidePic (){
showHideBrandPic.forEach(showHideBrandPic => {
if(showHideBrandPic.textContent === "ADIDAS BY PHARRELL WILLIAMS"){
pic.style.display = "none";
}else {
pic.style.display = "block";
}
})
};
showHidePic();
<h1 class="plp_brand_title">abc</h1>
<img class="hero_discription_container_left" src="/qw.png" alt="123" width="500" height="600">
<h1 class="plp_brand_title">ADIDAS BY PHARRELL WILLIAMS</h1>
<img class="hero_discription_container_left" src="/qw.png" alt="123" width="500" height="600">
這增加了一層功能,允許您設置一個文本數組來查找和隱藏圖像。
這個方法依賴于在classnames數組中的h1-with類之后總是有一個類為
.hero_discription_container_left
的映像。你把它們放在一個數組里,這樣就很容易把它們聯系起來。下面是另一個使用
element.nextElementSibling
的方法,它允許我們逐個遍歷元素。