0

My site has many buttons and many texts, the number of buttons and texts is the same, e.g if there are the nth number of buttons then there are the nth number of texts. My goal is to get the button index,i.e which button is clicked because based on that button index I want to show the same index/number text. e.g If I select the button having index 2 then I will show text that has index 2.

See code example:-

<div class="buttons">
  <button>Button 1</button>
  <button>Button 2</button>
  <button>Button 3</button>
  <button>Button 4</button>
  <button>Button 5</button>
  <button>Button 6</button>
  <button>Button 7</button>
  <button>Button 8</button>
</div>

<div class="text">
     <p>text 1</p>
     <p>text 2</p>
     <p>text 3</p>
     <p>text 4</p>
     <p>text 5</p>
     <p>text 6</p>
     <p>text 7</p>
     <p>text 8</p>
</div>

Here if the user clicks on button 1 then based on that I want to show text 1. How can I get that will nth-child is being clicked so that based on that nth-child I can show relevant nth-child of text.

I used this but it always returns -:-

$('.buttons button').click( ()=>{
        console.log($('.buttons button').index(this));
    });
});

I can achieve this using the same id but I want to achieve my goal without id.

How to achieve this? I tried a lot but didn't get any solution.

Ali Bhutta
  • 457
  • 5
  • 20

0 Answers0