简体   繁体   中英

show and hide display with same class using javascript

i am trying to choose which element to show and hide using javascript, i can't make change on html, the below javascript show error on "Cannot set property 'display' of undefined". How can i show and hide element which share same class?

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">

querySelectorAll targets all elements, you need to then specify which index you want affected.

example: use pic[0].style or pic[1].style instead of pic.style

 var showHideBrandPic = document.querySelectorAll("h1.plp_brand_title"); var pic = document.querySelectorAll('.hero_discription_container_left'); function showHidePic (){ showHideBrandPic.forEach((showHideBrandPic, i) => { if(showHideBrandPic.textContent === "ADIDAS BY PHARRELL WILLIAMS"){ pic[i].style.display = "none"; }else { pic[i].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">

If you want all the elements affected, either loop through or use JavaScript's built-in maps : What is the concept of Array.map?

This adds a layer of functionality allowing you to set an array of text to find and hide the image after.

This method relies on that there will always be an image with class .hero_discription_container_left that follows an h1 with class that is in the classnames array. You get both in an array so it's easy to associate them.

 window.addEventListener('load', () => { let removeImagesAfter = ["remove my image too", "remove ME", "ADIDAS BY PHARRELL WILLIAMS"].map(e => e.toLowerCase()); // for sake of comparisons, we convert these to lower case const classNames = ["plp_brand_title", "otherclass", "otherclass2"] let h1s = document.querySelectorAll("h1") let imgs = document.querySelectorAll("img.hero_discription_container_left") h1s.forEach((h1, i) => { if (classNames.filter(c => h1.classList.contains(c)).length === 0) return; imgs[i].style.display = removeImagesAfter.includes(h1.innerText.trim().toLowerCase()) ? 'none' : 'block'; }) })
 <h1 class="otherclass2">remove my image too</h1> <img class="hero_discription_container_left" src="/qw.png" alt="123" width="500" height="6"> <h1 class="plp_brand_title">abc</h1> <img class="hero_discription_container_left" src="/qw.png" alt="123" width="500" height="6"> <h1 class="plp_brand_title">ADIDAS BY PHARRELL WILLIAMS</h1> <img class="hero_discription_container_left" src="/qw.png" alt="123" width="500" height="6"> <h1 class="someotherclass">Not me</h1> <img class="hero_discription_container_left" src="/qw.png" alt="123" width="500" height="6"> <h1 class="otherclass">remove me</h1> <img class="hero_discription_container_left" src="/qw.png" alt="123" width="500" height="6">

Here's another method using element.nextElementSibling which allows us to iterate through the elements one after the other.

 window.addEventListener('load', () => { let removeImagesAfter = ["ADIDAS BY PHARRELL WILLIAMS"].map(e=>e.toLowerCase()); // for sake of comparisons, we convert these to lower case document.querySelectorAll("h1.plp_brand_title").forEach(h1 => { if (removeImagesAfter.includes(h1.innerText.trim().toLowerCase())) { let sibling = h1.nextElementSibling while (sibling && sibling.tagName !== 'IMG') { sibling = sibling.nextElementSibling } sibling.style.display = "none"; } else { h1.nextElementSibling.style.display = "block"; } }) })
 <h1 class="plp_brand_title">abc</h1> <img class="hero_discription_container_left" src="/qw.png" alt="123" width="500" height="6"> <h1 class="plp_brand_title">ADIDAS BY PHARRELL WILLIAMS</h1> <img class="hero_discription_container_left" src="/qw.png" alt="123" width="500" height="6">

The following will scan your markup for titles and images following a certain title and puts the results in the array els . There can be any number (including 0) of images in a section started by a title, provided the image has the given class hero_discription_container_left . els is then an array of arrays. Each sub-array will contain as a first value the style.display value that is to be applied on all following <img> elements in the same sub-array. In an inner forEach() loop these display values are then assigned to the individual <img> elements ( im ).

 window.addEventListener('load', () => { const brands = ["ADIDAS BY PHARRELL WILLIAMS"]; const els=[]; document.querySelectorAll("h1.plp_brand_title,img.hero_discription_container_left").forEach(el =>{ if (el.tagName==="H1") els.push([brands.includes(el.innerText)?"none":"block"]); else els[els.length-1].push(el); }); els.forEach(([disp,...imgs])=> imgs.forEach(im=>im.style.display=disp) ) })
 <h1 class="plp_brand_title">abc</h1> <img class="hero_discription_container_left" src="/qw.png" alt="123" width="500" height="6"> <h1 class="plp_brand_title">ADIDAS BY PHARRELL WILLIAMS</h1> <img class="hero_discription_container_left" src="/qw.png" alt="123" width="500" height="6">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM