javascriptarraysimagealt

Getting all image alt text values and appending into a list using vanilla JS


The following JS gives me a list of all the img alt text used on a webpage, showing either a name "name" or empty quotes "".

const altAtt = document.querySelectorAll("*[alt]");
const altText = Array.from(altAtt, (al, i) => al.getAttribute('alt'));

console.log(altText);

Question: How do I get all the images with alt="" or alt="some name" and add them to a unordered list injected into the DOM?

I can create the structure document.createElement('ul'); etc. But no idea where to start adding the information into the list. Somehow using li.innerHTML = altText[i];

Thanks in advance for any help.

I do have this using jQuery but really wish to write this in vanilla JS. The jQuery adds a Div element after each image which is what I want to eventually achieve with vanilla JavaScript :-)

$.each($("img"), function() {
    var altText = $(this).attr('alt');
    if (altText === "") {
        $(this).after("<div class=\"no-alt-text\">This image is decoration</div>");
    } else {
        $(this).after("<div class=\"show-alt-text\">This image ALT text is: " + altText + "</div>");
        $(function () {
            $("div.show-alt-text:contains(\"undefined\")").each(function () {
            $(this).removeClass("show-alt-text").html("<div class=\"empty-alt\">This image is missing an ALT attribute</div>");
            $('div:empty').remove();
        });
});
    }
});

Solution

  • I think this is close to what you are looking for.

    const imgElements = document.querySelectorAll("img");
    
    const showAltText = document.createElement("div");
    showAltText.classList.add("show-alt-text");
    
    const noAltText = document.createElement("div");
    noAltText.classList.add("no-alt-text");
    noAltText.innerHTML = "This image is decoration";
    
    
    for(let i = 0; i < imgElements.length; i++){
      var altText = imgElements[i].alt;
      
      if(altText === ""){
        imgElements[i].after(noAltText.cloneNode(true));
      }
      else{
        const element = showAltText.cloneNode(true);
        element.innerHTML = "This image ALT text is: " + altText;
        imgElements[i].after(element);
      }
    }
    <!-- Alt Text -->
    <img height="100" alt="test1" src="https://www.worldanvil.com/uploads/images/03220ab14fe9a946322a5329bd7977ad.png" />
    
    <!-- Alt Text -->
    <img height="100" alt="test2" src="https://www.worldanvil.com/uploads/images/03220ab14fe9a946322a5329bd7977ad.png" />
    
    <!-- Empty Alt Text -->
    <img height="100" alt="" src="https://www.worldanvil.com/uploads/images/03220ab14fe9a946322a5329bd7977ad.png" />
    
    <!-- No Alt Text -->
    <img height="100" src="https://www.worldanvil.com/uploads/images/03220ab14fe9a946322a5329bd7977ad.png" />