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", "");
    }
  });
});
3
  • Sort of the converse of stackoverflow.com/questions/42190142/…. Commented Sep 5, 2018 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) Commented Sep 6, 2018 at 5:12
  • Thanks for the solution, this is working for me. Commented Sep 6, 2018 at 5:30

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.