I have four divs that share the same class, with each having its own unique id. I also have four radios that control their opacity. When a radio is clicked, a relevant div appears (opacity = 1) and the other three divs become hidden.
Here’s my code.
<html>
<body>
<div id="div-one" class="my-divs"></div>
<div id="div-two" class="my-divs"></div>
<div id="div-three" class="my-divs"></div>
<div id="div-four" class="my-divs"></div>
<input type="radio" id="radio-one" name="div-radio" value="div-one"
onClick="changeOpacity(this.value);"/>
<input type="radio" id="radio-one" name="div-radio" value="div-two"
onClick="changeOpacity(this.value);"/>
<input type="radio" id="radio-one" name="div-radio" value="div-three"
onClick="changeOpacity(this.value);"/>
<input type="radio" id="radio-one" name="div-radio" value="div-four"
onClick="changeOpacity(this.value);"/>
<script>
function changeOpacity(divId) {
document.getElementById(divId).style.opacity = 1;
document.querySelectorAll(".my-divs:not(divId)").forEach((e) => {
e.style.opacity = 0;
});
}
</script>
</body>
</html>
But this doesn’t seem to work. I think the problem is in the .my-divs:not(divId)
part because I don’t know how to exclude an ID from the class selector. I’m expecting a solution using vanilla JS because I’m not familiar yet with JQuery and other libraries. Thanks
3
Answers
You’re close, The issue is with the :not() selector; it doesn’t work with a variable directly. Instead, you can use a combination of attribute selectors and template literals to dynamically exclude the element with the specified ID.
I have added some logic to this code, I hope it will be useful:
A simpler apprach would be to hide all the divs and then target the specific one you want and show that.
Note that the code quality can be improved by using unobtrusive event handlers bound in JS< not in HTML, and also by using CSS classes to toggle opacity, and finally by removing the duplicate
id
attributes which are invalid.Here’s a working version with the above changes made: