mswift
mswift

Reputation: 5

How to apply one function to multiple instances of a class

I want to apply this 'coupon-clipping' function to multiple elements on this page without making a separate function for each different element. On the code snippet I added, it works for my first "Buy 4, Save $2.00" but not for the "4 Coupons".

From my research I know that this

var coupon1 = document.querySelector('.coupon1');

just returns the FIRST instance of the coupon1 but I need to figure out how to apply that function to ALL elements of that class (say 20 elements of the coupon1 class).

var coupon1 = document.querySelector('.coupon1');
var coupon2 = document.querySelector('.coupon2');

coupon1 ? coupon1
  .addEventListener('click', function() {
    coupon1.remove();
    coupon2.classList.remove('hide-coupon');
  }) : false;
<div class="coupon-product coupon1">
  <span id="coupon">Buy 4, Save $2.00</span>
</div>

<div class="coupon-product-clipped hide-coupon coupon2">
  <span id="clipped-coupon">Buy 4, Save $2.00</span>
</div>


<div class="coupon-product coupon1">
  <span id="coupon">4 Coupons</span>
</div>
<div class="coupon-product-clipped hide-coupon coupon2">
  <span id="clipped-coupon">4 Coupons</span>
</div>

Upvotes: 0

Views: 476

Answers (4)

Ele
Ele

Reputation: 33726

You need to use document.querySelectorAll() and loop over the collection of elements to bind the click event.

document.querySelectorAll('.coupon1').forEach(function(elem) {
    elem.addEventListener('click', function() {...});
})

As @pointy mentioned, some enviroments don't support Array iteration methods on NodeList objects, so, you can use the function Array.from.

Array.from(document.querySelectorAll('.coupon1')).forEach(function(elem) {
    elem.addEventListener('click', function() {...});
})

Or something like this: Reference

var elements = document.querySelectorAll('.coupon1')
Array.from({ elements.length }, function(_, i) { return i}).forEach(function(index) {
    let elem = elements.item(index);
    elem.addEventListener('click', function() {...});
});

Upvotes: 2

AamirR
AamirR

Reputation: 12198

Apply to as many elements as you want using jQuery class selector, as such:

var elements = $(".coupon1")

Now you can bind click event, as such:

elements.click(function(){
    var clickedCoupon = $(this);
    var allOtherCoupons = $(".coupon1").not(this);
})

Upvotes: 0

Potemkin
Potemkin

Reputation: 76

$('.coupon1').click(function() { stuff here}) doesn't do the job?

You could imagine:

$('.coupon1').click(function() { 
   $(this).hide();
   $('.coupon2').show();
)})

or even with a common class 'coupon':

$('.coupon').click(function() { 
   $('.coupon1').toggle();
   $('.coupon2').toggle();
)})

to alternate but maybe not needed

Regard

Upvotes: 0

Emil
Emil

Reputation: 1295

$(".coupon1").each(function(idx, elem){
    elem.click(function()
    {
        ...
    });
});

Upvotes: 1

Related Questions