Ricardo Zea
Ricardo Zea

Reputation: 10283

Replace only one element and not all

Ok, I tried this myself before posting here, but at this point I ran into a wall.

I have a list of products, each product has an 'Add To Cart' button/image, and I want that image to be replaced with the 'Item added to Cart' image.

The problem I have is that when I replace one image, all images are replaced. You can now tell how new to jQuery I am.

This is my jQuery:

//Replace the 'Add To Cart' button
 $('.add-to-cart-btn').click(function(){
   $('.add-to-cart-btn').replaceWith('<img src="images/button-added-to-cart.png" alt="Item added to Cart">');
 return false;
 });

Here's my HTML:

<a href="#" class="add-to-cart-btn"><img src="images/button-add-to-cart.png" alt="Add to Cart"></a>

As you can see, I'm replacing the entire ahref element because when the item is added, I don't want that button to be clickable again.

Any idea how to make just that one specific 'Add To Cart' button/image get replaced and not all the buttons?

Thanks for any help and guidance you can give me.

Upvotes: 2

Views: 434

Answers (2)

Marcus Whybrow
Marcus Whybrow

Reputation: 19998

I think a more efficient way to do this would be:

$('.add-to-cart-btn').click(function() {
    this.src = 'images/button-added-to-cart.png';
    this.alt = 'Item added to Cart';
    return false;
});

Upvotes: 1

JasCav
JasCav

Reputation: 34632

You want to only replace the item that you selected (AKA, the item that was clicked), so don't do the selection again and instead use the object that was clicked (this).

//Replace the 'Add To Cart' button
 $('.add-to-cart-btn').click(function(){
   $(this).replaceWith('<img src="images/button-added-to-cart.png" alt="Add to Cart">');
 return false;
 });

Upvotes: 3

Related Questions