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
You can achieve it via
getElementsByClassName
, see below:Or you could use
querySelectorAll(".sect")
instead if you prefer.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 usegetElementsByClassName("firstRow")[0]
or usequerySelector
instead.And don’t forget to use class for the button as it not recommended to use the same id for multiple elements.