Reduce operation

Asked

Viewed 44 times

0

Follows my code:

function yvlcs() {

        var buttonsYv = [];

        document.querySelectorAll('.yv-container-ul li').forEach(function (e) {
            buttonsYv.push(e);
            e.addEventListener('click', function (e) {
                if(e.path[0].className == "") {
                    buttonsYv[0].removeAttribute('class');
                    buttonsYv[1].removeAttribute('class');
                    this.className = "yv-btn-active";
                }
            })
        });
    }

yvlcs()

Look at the buttonsYv[0].removeAttribute('class'); and the buttonsYv[1].removeAttribute('class');

You’d be able to put that together in one line, just to use one removeAttribute('class') instead of two?

EDIT

I didn’t want to remove with foreach, because this way I already did, I want to know if there are any other alternatives, that look like css for example, that we can use the comma and take more than one element:

.elemento1,
.elemento2 {
    display: none; 
}
  • You will always remove only the 2 elements index[0] and the index[1], what happens if this variable has more indices ?

2 answers

0

Since you want to do this from a certain amount the ideal would be to use the repeating structure for:

var i;
for (i = 0; i < 2; i++) { 
  buttonsYv[i].removeAttribute('class');
}

  • Good evening, my question has been edited.,

0

To stay in a row only you can do so:

buttonsYv.forEach(x => x.removeAttribute('class'));

I hope I’ve helped!

  • 1

    Wesley, this is a good output, but the author of the question does not make it clear whether he wants to remove the attribute from all elements of the array. Unfortunately the question is vague and it is difficult to guess what exactly the author wants if he does not express himself better. That said, it is worth adding more information in your answer so that it is clear what it does and the problems that may occur in case only the 1st and 2nd elements of the array should be changed.

  • Good evening, my question has been edited.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.