I'm very new and just a programming enthusiast so I don't know a lot. I'm building a site where I need to click a button and then have a bunch of other buttons appear clicked. The other buttons don't have any functions when clicked, it's just the change of CSS class to appear "clicked".
So in summary, I need to click the first button, and then on the other side of the page I have 125 buttons which I need to appear "clicked" as well (not all 125, just some). And then when I "unclick" the first button, then they all "unclick" also. It's like toggling some of the buttons with just one.
I have tried any way I know of changing the class of the second buttons when I click the first one. I have tried something like this selecting each individual button by the ID:
const gridTriangleOne = document.querySelector('.gridTriangleOne');
const numberTest = document.getElementById('111');
gridTriangleOne.addEventListener('click', myFunction);
function myFunction() {
numberTest.classList.add('active2');
};
I have tried something like this:
const gridTriangleOne = document.querySelector('.gridTriangleOne');
const triangleOne = document.querySelectorAll('.triangleOne');;
gridTriangleOne.addEventListener('click', () =>
triangleOne.forEach(triangleOne => {
triangleOne.classList.toggle('active');
})
);
or even a different variation of the above with add instead of toggle. Nothing really works. Thanks for the help.
this is just a little cleaner and takes out some unneeded code from the first answer.
document.querySelector(".clickme").addEventListener("click", function() {
const allPoorElements = document.getElementsByClassName("click");
for (let i = 0; i < allPoorElements.length; i++) {
allPoorElements[i].classList.toggle("clicked");
}
});
.clicked {background-color: #4CAF50;} .clicked, .clickme, .click { background-color: #4CAF50; border: none; color: white; padding: 16px 32px; font-size: 16px; } .clicked { background-color: lightgreen; border: none; color: black; padding: 16px 32px; font-size: 16px; }
<button class="clickme">clickme</button>
<button class="click">1</button>
<button class="click">2</button>
<button class="click">3</button>
<button class="click">4</button>