Answer the question
In order to leave comments, you need to log in
How to optimize javascript code?
How to optimize javascript code?
It is necessary that when button 1 is pressed, the color of div 1 changes, when button 2 is pressed, the color of div 2 changes, and so on. At the same time, I can’t wrap them in a container, because on the site, these will be elements from different sections.
here is a simplified example :
https://codepen.io/mk3mk/pen/ZwQxMg?editors=0110
I want to put a variable instead of indexes, but I can't figure out how to do it
yes, and yet, this must be done in pure js
Answer the question
In order to leave comments, you need to log in
You can link elements through additional attributes. For example .
UPD. Taken from the comments:
maybe you can somehow, so that, for example, the button with index 1 is pressed, it means that the div with index 1 changes there
document.addEventListener('click', ({ target: el }) => {
if (el.classList.contains('button')) {
const index = [...document.querySelectorAll('.button')].indexOf(el);
document.querySelectorAll('.div')[index].classList.toggle('red');
}
});
const divs = document.querySelectorAll('.div');
document.querySelectorAll('.button').forEach((n, i) => {
n.addEventListener('click', () => divs[i].classList.toggle('red'));
});
only one div needs to be "changed" at a time
document.addEventListener('click', ({ target: el }) => {
if (el.classList.contains('button')) {
const index = [...document.querySelectorAll('.button')].indexOf(el);
document.querySelectorAll('.div').forEach(({ classList: cl }, i) => {
cl.toggle('red', i === index && !cl.contains('red'));
});
}
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question