vendredi 9 février 2018

jQuery - If hasClass but for multiple elements

This is bit hard to explain, but here goes nothing:

I have .wrapper that holds 50 elements with no clicking events.

On another place I have randomly loaded 5 elements out of that 50.

Now what I'm trying to do is see which 5 random elements showed up so I could turn them as clicking objects within the .wrapper.

For example, this is the wrapper with elements:

<div class="wrapper">
  <div class="object1"></div>
  <div class="object2"></div>
  <div class="object3"></div>
  <div class="object4"></div>
  <div class="object5"></div>
  <div class="object6"></div>
  <div class="object7"></div>
  <div class="object8"></div>
  <div class="object9"></div>
  <div class="object10"></div>
  <!-- and so on -->
</div>

And this is random container:

<div class="random">
  <div class="object7"></div>
  <div class="object9"></div>
  <div class="object5"></div>
  <div class="object6"></div>
  <div class="object1"></div>
</div>

I've tried it like this and it works but it will work only for the first one that I called and besides, there has to be a better way.

if ($('.random div').hasClass(".object1")){
  $(".wrapper .objects1").on("click", function() {
    // do things
  });
}

if ($('.random div').hasClass(".object2")){
  $(".wrapper .objects2").on("click", function() {
    // do things
  });
}

if ($('.random div').hasClass(".object3")){
  $(".wrapper .objects3").on("click", function() {
    // do things
  });
}

// and so on (until 50...)




Aucun commentaire:

Enregistrer un commentaire