Gavin Friel
Gavin Friel

Reputation: 125

Assign Uinque IDs to elements and target with JQuery

I have a list of elements that are styled by CSS classes. I need to target these elements individually with JQuery.

For example I have a class .pass-fail-icon that uses JQuery .hasClass() as such:

// Method simply swaps out image based on .hasClass() result
function checkPassed() {
  if ($(".pass-fail-icon").hasClass("passed")) {
    var failSrc = 'img/Fail.svg';
    var passSrc = 'img/Pass.svg';
    $('img[src="' + failSrc + '"]').attr('src', passSrc);

  } else {
    var failSrc = 'img/Fail.svg';
    var passSrc = 'img/Pass.svg';
    $('img[src="' + passSrc + '"]').attr('src', failSrc);

  }
}

however I need to target .pass-fail-icon individually as I cannot determine yet how long a list will be generated.

How do I give .pass-fail-icon a unique ID, and how then do I target it in the above method?

Upvotes: 0

Views: 24

Answers (2)

Preli
Preli

Reputation: 3031

I don't think you need Ids for what you are trying to do.

var failSrc = 'img/Fail.svg';
var passSrc = 'img/Pass.svg';

//get all pass-fail-icons which don't have a class .passed
$(".pass-fail-icon:not(.passed)").attr('src', failSrc);

//get all pass-fail-icons with a class .passed
$(".pass-fail-icon.passed").attr('src', passSrc);

Or the following should work as well

$(".pass-fail-icon").attr('src', failSrc);
$(".pass-fail-icon.passed").attr('src', passSrc);

Assign all icons the failSrc and override all that have passed with the passSrc

Upvotes: 1

Sebastian Speitel
Sebastian Speitel

Reputation: 7346

You can use .each() to iterate through the elements. And you shouldn't create the two variables each time.

function checkPassed() {

  var failSrc = 'img/Fail.svg';
  var passSrc = 'img/Pass.svg';

  $(".pass-fail-icon").each(function() {

    if ($(this).hasClass("passed")) {
      $('img[src="' + failSrc + '"]').attr('src', passSrc);
    } else {
      $('img[src="' + passSrc + '"]').attr('src', failSrc);
    }
  });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 0

Related Questions