Skip to content Skip to sidebar Skip to footer

How To Check If An El Has A Class That Matches A Value In Array?

I have an array and some path elements. I need to check if the class of a path matches one of the values in my array and if so add a class fadeIn to it, I tried this:

Solution 1:

You need to use document ready function rest of the things are already fine. You just missed document ready function. Here is the running code:

<style>.fadeIn {
        color: red;
    }
</style><scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script>
$(document).ready(function (){
    var nationList = ["usa", "france", "italy"];
    var foundNations = $.unique(nationList.sort());
    $("path").each(function() {
      for (var i = 0; i < foundNations.length; i++) {
        if ($(this).hasClass(foundNations[i])) {
          $(this).addClass("fadeIn");
        }
      }
    });
});
</script><pathclass="spain">Spain</path><pathclass="italy">Italy</path><pathclass="germany">Germany</path><pathclass="usa">USA</path>

Solution 2:

.includes function can check array value exist with provided value. If exist it return true ...So you can use that for your nationList array ..

var nationList = ["usa", "france", "italy"];

$("path").each(function(){
   if(nationList.includes($(this).attr('class'))) {
    $(this).addClass('fadeIn');
   }
});
.fadeIn {
  color: red;
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><pathclass="spain">Spain</path><pathclass="italy">Italy</path><pathclass="germany">Germany</path><pathclass="usa">Usa</path>

Post a Comment for "How To Check If An El Has A Class That Matches A Value In Array?"