You need to enable JavaScript to run this app. 如何用JavaScript控制相同class元素显隐,解决display设置undefined报错
优惠活动
大模型
产品
解决方案
定价
更多

如何用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 18:48:04