Javier Ventureira
Javier Ventureira

Reputation: 29

Toggle elements from classes with JS

I would like to show more information when someone click on show more buttons. The complication is that there are several buttons and informations to toggle with same className. What am I doing wrong??

var element = document.querySelectorAll("btn");
for (var i = 0; i < button_length ; i++) {
   element[i].addEventListener("click", function() {
   alert("Button Clicked " + i);
   element[i].classList.toggle("extrainfo");
};
}
 td{border:solid 1px black;}
 .btn, #btn_id{color:blue; text-decoration:underline; cursor:pointer;}
 
.extrainfo{
  display:none
}
<table>

  <tbody>
    <tr class="info_group">
      <td>Title 1</td>
      <td class="btn">show more</td>
    </tr>
    <tr>
      <td class="extrainfo" colspan="2">More info 1</td>
    </tr>
   </tbody>
   
     <tbody>
    <tr class="info_group">
      <td>Title 2</td>
      <td class="btn">show more</td>
    </tr>
    <tr>
      <td class="extrainfo" colspan="2">More info 2</td>
    </tr>
   </tbody>
   
     <tbody>
    <tr class="info_group">
      <td>Title 3</td>
      <td class="btn">show more</td>
    </tr>
    <tr>
      <td class="extrainfo" colspan="2">More info 3</td>
    </tr>
   </tbody>
  
</table>

Upvotes: 0

Views: 36

Answers (1)

Razin
Razin

Reputation: 109

to work you javaScript

var element = document.querySelectorAll("btn"); // need to be (".btn")

// you want it to be i < element.length; ? or there's a variable called button_length?
for (var i = 0; i < button_length ; i++) { 
       element[i].addEventListener("click", function() {
       alert("Button Clicked " + i);
       element[i].classList.toggle("extrainfo");
    }; // missing a Parenthesis need to be this }); not this };
    }

I'm still not sure about the functionality, but see the code below if that's what you're looking for.

var element = document.querySelectorAll(".btn");
var extraInfo = document.querySelectorAll(".extrainfo");

for (let i = 0; i < element.length; i++) {
   element[i].addEventListener("click" , function() {
   extraInfo[i].classList.toggle("extrainfo");
   });
}

hereJSFiddle you can play around with the code

Upvotes: 1

Related Questions