skip to Main Content

I have a set of buttons inside multiple div classes. When any button in a particular div class is pressed I want wrong to pop up. I’m confused on how to access. I tried using document.getElementsbyClassName() but this does not work is there another way. heres what I currently have inside the body.

<div class='container'>
        <div class='sections'>

            <div class='firstRow'>
                <button id="sect">cat1</button>
                <button id="sect">cat2</button>
                <button id="sect">cat3</button>
            </div>
    </div>
</div>
<script>
    var btn = document.getElementsByClassName("firstRow");
    btnContainer[0].addEventListener("click", function (){console.log("wrong"); }); 
</script>

2

Answers


  1. You can achieve it via getElementsByClassName, see below:

    <div class='container'>
            <div class='sections'>
    
                <div class='firstRow'>
                    <button id="sect">cat1</button>
                    <button id="sect">cat2</button>
                    <button id="sect">cat3</button>
                </div>
        </div>
    </div>
    <script>
        var btns = document.getElementsByClassName("firstRow");
        for (let btn of btns) btn.addEventListener("click", function (){alert("wrong"); }); 
    </script>

    Or you could use querySelectorAll(".sect") instead if you prefer.

    Login or Signup to reply.
  2. The getElementsByClassName method returns a set of elements with the class name, not a single element. If you want to target the buttons inside the .firstRow div, you should use getElementsByClassName("firstRow")[0] or use querySelector instead.

    <div class='container'>
      <div class='sections'>
        <div class='firstRow'>
          <button class="sect">cat1</button>
          <button class="sect">cat2</button>
          <button class="sect">cat3</button>
        </div>
      </div>
    </div>
    
    <script>
      var btnContainer = document.getElementsByClassName("firstRow")[0];
      btnContainer.addEventListener("click", function () {
        alert("wrong"); 
      });
    </script>

    And don’t forget to use class for the button as it not recommended to use the same id for multiple elements.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search