Search code examples
javascripthtmlcssradio-button

How to hide all elements with the same class and show one particular id from that class using a radio button?


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


Solution

  • 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.

    <html>
      <body>
        <div id="div-one" class="my-divs">1</div>
        <div id="div-two" class="my-divs">2</div>
        <div id="div-three" class="my-divs">3</div>
        <div id="div-four" class="my-divs">4</div>
    
        <input type="radio" id="radio-one" name="div-radio" value="div-one"      
        onClick="changeOpacity(this.value);"/>
        <input type="radio" id="radio-two" name="div-radio" value="div-two"      
        onClick="changeOpacity(this.value);"/>
        <input type="radio" id="radio-three" name="div-radio" value="div-three"      
        onClick="changeOpacity(this.value);"/>
        <input type="radio" id="radio-four" 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([id="' + divId + '"])').forEach((e) => {
              e.style.opacity = 0;
            });
          }
        </script>
      </body>
    </html>