i need to "move" active class one by one to this 5 div elements but with very basic js because still learning basics, i found this solution and it work but i want transform this in a for loop,it is possible without any function,foreach loop,only with very basics? thanks
this is my solution:
next.addEventListener('click', function(){
let current = document.querySelector('.active')
if(current.classList.contains('active')){
imgItems[1].classList.add('active')
imgItems[0].classList.remove('active')
}
if (current.classList.contains('active')) {
imgItems[1].classList.remove('active')
imgItems[2].classList.add('active')
}
if (current.classList.contains('active')) {
imgItems[2].classList.remove('active')
imgItems[3].classList.add('active')
}
if (current.classList.contains('active')) {
imgItems[3].classList.remove('active')
imgItems[4].classList.add('active')
}
})
I try many times and online solutions is nice but too advanced for me,i have learning only array and cycle.
2
Answers
Assuming the items are adjacent in the DOM, you can use
nextElementSibling
to go to the next item.Here you go
Javascript has no foreach loop. It has for .. in loop, for .. of loop and normal C-style loop. In this case I have used the latter because we are to work with indexes.
It seems that you intend to cascade the
active
class towards the end of someimgItems
set, so the idea is to loop anindex
from 0 up to 3 and each time to check whethercurrent
has anactive
class, then remove that class from the actual element on the index we are currently on and add this class to the next. You can also do it without a loop, like this:Basically we convert the array-like object called
imgItems
to an array using the spread operator (the […] part) and inside the event, you get the index of current in the array and if it’s not the very last one, you remove the active class and add it to the next.