简体   繁体   中英

Click to change image across multiple items

I'm trying to set up a javascript function that will take a down arrow image and swap it with an up arrow image when clicked. It worked when the image had an id, but because I have a couple menu items that uses the arrow image, I wanted to try to get it to work as a class name or just regular name, but I can't get the function to change the source of the image when it's not an id. Can anyone help? Here is my current HTML markup:

<div class="header__links hide-for-mobile" >
                <a id="subMenu" href="#">Features <img class="downArrow" src="/assets/images/icon-arrow-down.svg"></a>
                <a href="#">Company</a>
                <a href="#">Careers</a>
                <a href="#">About</a>
            </div>

And here is my JS

const subMenu = document.querySelector('#subMenu');
subMenu.addEventListener('click', function() {
    if(subMenu.classList.contains('subOpen')) {
        subMenu.classList.remove('subOpen');
        document.getElementsByClassName('downArrow').src="/assets/images/icon-arrow-down.svg";
    }

    else {
        subMenu.classList.add('subOpen');
        document.getElementsByClassName('downArrow').src="/assets/images/icon-arrow-up.svg";
    }
})

Right now since your markup only contains a single element with the downArrow class you could update your code to:

const subMenu = document.querySelector('#subMenu');
subMenu.addEventListener('click', function() {
    if(subMenu.classList.contains('subOpen')) {
        subMenu.classList.remove('subOpen');
        document.getElementsByClassName('downArrow')[0].src="/assets/images/icon-arrow-down.svg";
    }

    else {
        subMenu.classList.add('subOpen');
        document.getElementsByClassName('downArrow')[0].src="/assets/images/icon-arrow-up.svg";
    }
})

But a better way to do this would be to loop through the results of the getELementsByClassName method. You could do that with something like:

const subMenu = document.querySelector('#subMenu');
subMenu.addEventListener('click', function() {
    if(subMenu.classList.contains('subOpen')) {
        subMenu.classList.remove('subOpen');
        Array.from(document.getElementsByClassName("downArrow")).forEach(
            function(element, index, array) {
                element.src="/assets/images/icon-arrow-down.svg";
            }
        );
    }

    else {
        subMenu.classList.add('subOpen');
        Array.from(document.getElementsByClassName("downArrow")).forEach(
            function(element, index, array) {
                element.src="/assets/images/icon-arrow-up.svg";
            }
        );
    }
})

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