I am trying to write a code that toggles the styling of a button. At first, I thought I could do this with CSS and the active selector. But I also want to be able to undo the changes on click, which the active selector does not. Then I thought I might be able to do this with JavaScript and a class toggle function.
Unfortunately, I am not that familiar with JavaScript. I have written a code and it partially works, but it always changes the styling of the same element (maybe because it is the first element with the specific class?).
Is there a way to build a flexible function which can apply to several elements, depending on which one I click on?
function testtoggle() {
if(document.getElementById("testknop").className == "nietactief"){
document.getElementById("testknop").className = "actief";
} else {
document.getElementById("testknop").className = "nietactief";
}
}
button {
cursor: pointer;
padding: 16px;
font-size: 16px;
border-radius: 100%;
}
.nietactief {
background-color: #a8a8a8;
border: 5px solid #ddd;
}
.actief {
background-color: purple;
border: 5px solid green;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button type="button" id="testknop" class="nietactief" onclick="testtoggle()()">1e</button>
<button type="button" id="testknop" class="nietactief" onclick="testtoggle()">2e</button>
<button type="button" id="testknop" class="nietactief" onclick="testtoggle()()">3e</button>
</body>
</html>