Skip to content Skip to sidebar Skip to footer

Jquery Add Alt Tag To Images With Same Src

There are many images with same URL source but the first image only that has the Alt tag, so how can I add alt to the other image with the same source? Simply I need filter images

Solution 1:

  1. get all unique src attributes,
  2. for each unique src attribute, get all images that use it
  3. for each set, find a member with alt and then assing that to the entire set.

In code:

const uniques = [];
const imgs = $('img');

imgs.each(function () {
  let src = this.src;
  if (uniques.indexOf(src) === -1) uniques.push(src);
});

uniques.forEach(src => {
  let srcd = imgs.filter("img[src='"+src+"']");
  let alt = srcd.filter('[alt]').first().attr('alt');

  srcd.each( function() {
    $(this).attr('alt',alt);
  })
});

Solution 2:

The first version (with comments) assigns the value of only the first instance of alt to all images:

$(function () {
    // Get value of first instance of 'alt' for images within elements of the given classvar alt = $(".colourDots img[alt]").first().attr("alt");
    // If value of 'alt' is not null or undefined// (Note, use != and not !== for this test)if (alt != null) {
        // Iterate images within elements of class .colourDots
        $.each($(".colourDots img"), function () {
            // assign value of var alt to each image
            $(this).attr("alt", alt);
        });
    }
});

and the second version assigns the alt value of the element to subsequent images (so alt="bbb" in your question is picked up and assigned to subsequent images):

$(function () {
    // Define a holding variablevar alt;
    // Iterate images
    $.each($(".colourDots img"), function () {
        // If element has 'alt', assign the value to var altif ($(this).attr("alt") != null) {
            alt = $(this).attr("alt");
        }
        // otherwise assign the value of var alt to the imageelse {
            $(this).attr("alt", alt);
        }
    });
});

You can take your pick, depending on what your specific needs are.

Post a Comment for "Jquery Add Alt Tag To Images With Same Src"