Home > Software engineering >  I want to add the class just in the clicked span
I want to add the class just in the clicked span

Time:12-05

when I tried to use jQuery it changes every span with the same class but I don't want to add an id for each span

$(".pay-btn").click(function (e) { 
        e.preventDefault();
        $(".bay-btn").addClass('bay-btn-clicked');
    });

I want to add a class to the clicked span without the unclicked yet

        <div >
            <div ><img src="/src/shop/imgs/black-sh.jfif" alt=""></div>
            <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Eius esse consequatur magnam exercitationem quisquam.</p>
            <span >10$</span>
            <span >Bay</span>
        </div>
        <div >
            <div ><img src="/src/shop/imgs/red-sh.jfif" alt=""></div>
            <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Eius esse consequatur magnam exercitationem quisquam.</p>
            <span >10$</span>
            <span >Bay</span>
        </div>

CodePudding user response:

You can use the this keyword to target the clicked element. The this keyword refers to the element that triggered the event. Here's how you can use it in your code:

$(".pay-btn").click(function (e) { 
  e.preventDefault();
  // Use 'this' to target the clicked element
  $(this).addClass('bay-btn-clicked');
});

CodePudding user response:

It seems that you misspelled the class name ".pay-btn" and ".bay-btn" in jQuery, so the code would be:

$(".pay-btn").click(function (e) { 
        e.preventDefault();
        $(".pay-btn").addClass('pay-btn-clicked');
    });

And dont forget to update the class names in HTML file as well: bay-btn -> pay-btn

  • Related