This is my code, buttons are creating dynamically
<button class="same_name" onclick='myfunction()'>button name</button>
<button class="same_name" onclick='myfunction()'>button name</button>
<button class="same_name" onclick='myfunction()'>button name</button>
<button class="same_name" onclick='myfunction()'>button name</button>
and I want to add class to button which I clicked
function myfunction()
{
$(this).addClass("active");
}
If you're using jQuery, and you're adding the buttons dynamically, strip out the inline JS, and use event delegation to attach one listener to a parent container to watch for events from your same_name buttons, and then add a class for that clicked button. (I'm using toggleClass in this example.)
$(document).on('click', '.same_name', function () {
$(this).toggleClass('active');
});
.active { color: red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="same_name">button 1</button>
<button class="same_name">button 2</button>
<button class="same_name">button 3</button>
<button class="same_name">button 4</button>
Andy's solution is the proper one. If you wish to roll with your own solution, just pass the event to the function.
function myfunction(event){
let eTar = event.target
$(eTar).addClass("active");
}
.active { color: red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="same_name" onclick='myfunction(event)'>button name</button>
<button class="same_name" onclick='myfunction(event)'>button name</button>
<button class="same_name" onclick='myfunction(event)'>button name</button>
<button class="same_name" onclick='myfunction(event)'>button name</button>
Here's the vanilla JS answer (jQuery isn't necessary at all, for almost nothing in 2022):
document.addEventListener('click', function ({target}) {
if (target.matches('button.same_name')) target.classList.add('active');
});
.active { color: red; }
<button class="same_name">button 1</button>
<button class="same_name">button 2</button>
<button class="same_name">button 3</button>
<button class="same_name">button 4</button>