0

Been trying add alt text in the web page using jquery below code however able to get correct value for the 1st image but else if and else conditions are not working properly. Not able to add alt texts for the other images

$(document).ready(function() {

  $("img ").each(function() {
    var img = $(this);

    if (!img.attr("alt") || img.attr("src") === "/temp/iconcache/flags/32x32/flag_brazil.png")
      img.attr("alt", "Brazil Flag");
    else if (!img.attr("alt") || img.attr("src") === "/temp/iconcache/flags/32x32/flag_China.png")
      img.attr("alt", "China Flag");
    else {
      img.attr("alt", "");
    }
  });
});
Jacob
  • 77,566
  • 24
  • 149
  • 228
Abhilash Poojary
  • 127
  • 1
  • 2
  • 11
  • Sort of the converse of https://stackoverflow.com/questions/42190142/whats-wrong-with-my-if-else-statement. – T.J. Crowder Sep 05 '18 at 17:24
  • 1
    Here you go: `$("img").each(function() { var img = $(this); if (!img.attr("alt") && img.attr("src") === "/temp/iconcache/flags/32x32/flag_brazil.png") img.attr("alt", "Brazil Flag"); else if (!img.attr("alt") && img.attr("src") === "/temp/iconcache/flags/32x32/flag_China.png") img.attr("alt", "China Flag"); else { img.attr("alt", ""); } });` You can also use `indexOf` to check if src contains a text. eg: `if(!img.attr("alt") && img.attr("src").indexOf("flag_brazil.png") !== -1)` – Prasanna Jathan Sep 06 '18 at 05:12
  • Thanks for the solution, this is working for me. – Abhilash Poojary Sep 06 '18 at 05:30

1 Answers1

1

You're using || when you want &&. Each of your conditions has if (!img.attr("alt") || ... which means that if the image's alt attribute is null, the remainder of the conditional expression will be ignored. This means a null alt will cause the first branch ("brazil") to be run, regardless of the value of the src attribute.

user229044
  • 232,980
  • 40
  • 330
  • 338
  • You could also add an `if (!img.attr('alt')) return;` before the other ifs to short-circuit the rest of the code. That way you don't have to repeat that check. – Jacob Sep 05 '18 at 17:26