Search code examples
javascriptloopsforeachnodelist

remove styles from all nodelist element and add only to clicked element Vanilla JS


I have multiple divs that when clicked adds a border and scales them up a little. I am looping through all elements using foreach and on click i remove every element's border and scale property except the clicked element, to which i add a border and scale. My code is completely logical and is supposed to work but for some reason i cant seem to grasp, it only applies the styles to clicked elements but not removing from the rest of the elements (like my code says it should).

JS

    document.querySelectorAll('.projcolorpick div').forEach(el => {
            el.onclick = (e) => {
                el.style.border = "none"
                el.style.transform  = "scale(1)"
                e.target.style.border = "2px solid #fff"
                e.target.style.transform = "scale(1.2)" 
                projcolor = e.target.style.background   
            }
        }) 
     } 

Solution

  • give something like this a try... each element needs an id attribute for this to work (the filter part - if there is a unique attribute...)

        const list = Array.from(document.querySelectorAll('.projcolorpick div'));
        list.forEach(el => {
                el.addEventListener('click', (e) => {
                    //code that affects the element you click on
                    el.style.border = "2px solid #fff"
                    el.style.transform = "scale(1.2)" 
                    projcolor = e.target.style.background;
                    list.filter(x=>x.id!=el.id).forEach(otherEl=>{
                        //code that affects the other elements you didn't click on
                        otherEl.style.border = "none"
                        otherEl.style.transform  = "scale(1)"
                    });
                });
            }); 
         
        ```
    edit:
    fixed some typos.