如何用JavaScript控制相同class元素显隐,解决display设置undefined报错
报错根因
你调用document.querySelectorAll()返回的是符合选择器的所有元素组成的NodeList类数组集合,不是单个DOM元素,集合本身没有style属性,直接访问pic.style自然会触发Cannot set property 'display' of undefined报错。
解决方法
你的HTML结构中h1.plp_brand_title和.hero_discription_container_left是按顺序一一对应的,遍历标题集合时可以通过索引拿到对应的图片元素,单独控制显隐即可,修正后的代码如下:
var showHideBrandPic = document.querySelectorAll("h1.plp_brand_title"); var pic = document.querySelectorAll('.hero_discription_container_left'); function showHidePic (){ // 遍历的时候拿到当前元素的索引index showHideBrandPic.forEach((currentTitle, index) => { // 加trim避免前后空格导致匹配失败 if(currentTitle.textContent.trim() === "ADIDAS BY PHARRELL WILLIAMS"){ // 通过索引取对应位置的图片元素操作样式 pic[index].style.display = "none"; }else { pic[index].style.display = "block"; } }) }; showHidePic();
如果你的实际场景中标题和图片不是严格按索引对应的,可以在遍历到符合条件的标题时,用nextElementSibling拿到它后面紧跟的图片元素,适配性更强:
var showHideBrandPic = document.querySelectorAll("h1.plp_brand_title"); function showHidePic (){ showHideBrandPic.forEach(currentTitle => { // 直接拿当前标题后紧跟的同级元素(就是对应的img) const targetPic = currentTitle.nextElementSibling; if(currentTitle.textContent.trim() === "ADIDAS BY PHARRELL WILLIAMS"){ targetPic.style.display = "none"; }else { targetPic.style.display = "block"; } }) }; showHidePic();
内容的提问来源于stack exchange,提问作者Charmaine Ho
相关产品推荐
相关产品推荐

