I have a dynamic html template. Which forms when I click on a button. Now, the problem is When I click on one button all buttons are clicked



Here is the html template forms when I click on a button.

<div class="detail">
                    <h3>${element.name}</h3>
                    <p>Phone: ${element.phone}</p>
                    <button onclick="addToHistory()">Call</button>
                </div>`

Let’s say it creates two template as it is.

<div class="detail">
                        <h3>Person1</h3>
                        <p>Phone: 0111111111</p>
                        <button onclick="addToHistory()">Call</button>
                    </div>`

<div class="detail">
                        <h3>Person2</h3>
                        <p>Phone: 0111111111</p>
                        <button onclick="addToHistory()">Call</button>
                    </div>`

Now, I want to click on one button and then according to my click I want the data of clicked divs should store.

I tried this using event handler as you can see with addToHistory() function. But, it stores all the data both I clicked and not clicked also.

Please note: I want to do this only using JavaScript. Thank you for your support.

Answer

You can pass this into your method and use that to traverse within the specific detail container where the button was clicked.

this will reference the specific element the event occurs on

function addToHistory(el){
   console.log(el.previousElementSibling.textContent);
}
<div class="detail">
  <h3>Person1</h3>
  <p>Phone: 0999999999</p>
  <button onclick="addToHistory(this)">Call</button>
</div>`

<div class="detail">
  <h3>Person2</h3>
  <p>Phone: 0111111111</p>
  <button onclick="addToHistory(this)">Call</button>
</div>`


Source: stackoverflow