You need to begin by splitting up the code where you assign the click handlers.
To avoid unnecessary queries, you can query once and then use the results later multiple times.
const main = document.querySelector('#all');
const ones = document.querySelectorAll('.one');
Then assign the handler to the button that toggles them all. It will toggle them by iterating over the elements you got further up.
I am assuming you also want to toggle the "main" button, if not, remove that line.
main.addEventListener('click', function (e) {
e.target.style.backgroundColor = "red";
ones.forEach( el => {
el.style.backgroundColor = "red";
});
});
Then the "toggle one" buttons, iterate over them and assign a handler that only affects the element clicked.
ones.forEach( el => {
el.addEventListener('click', function (e) {
e.target.style.backgroundColor = "red";
});
});
const main = document.querySelector('#all');
const ones = document.querySelectorAll('.one');
const updatedColor = 'red';
const originalColor = main.style.backgroundColor;
main.addEventListener('click', function (e) {
updateColor(e.target);
ones.forEach( el => {
updateColor(el);
});
});
ones.forEach( el => {
el.addEventListener('click', function (e) {
updateColor(el);
});
});
// Update the element color based on the current color
function updateColor(el) {
if (el.style.backgroundColor === originalColor) {
el.style.backgroundColor = updatedColor;
} else {
el.style.backgroundColor = originalColor;
}
}
<button id="all" type="button">All</button>
<button class="one" type="button">A</button>
<button class="one" type="button">B</button>
<button class="one" type="button">C</button>
UPDATE: to handle going back to the original color on second, or any even number, clicks, we can first store the original color in a constant.
const originalColor = main.style.backgroundColor;
And then use that constant, to update the button background color conditionally, better to do it in a separate function, to avoid repetition.
function updateColor(el) {
if (el.style.backgroundColor === originalColor) {
el.style.backgroundColor = updatedColor;
} else {
el.style.backgroundColor = originalColor;
}
}