Automatically Add the Image Alt Attribute with JavaScript

12/27/2021

Contents

In this article, you will learn how to add the alt attribute to the image automatically with JavaScript.

Get the img element

Gets the img element in the document.
In order to get all existing tags, specify the tag instead of id or class to get the element.

HTML

<img src="#">
<img src="#">
<img src="#">

JavaScript

const imgs = document.getElementsByTagName('img');

Determine if the img element has an alt attribute

Determines if each img element present in the document has an alt attribute.
Use hasAttribute to determine the attribute.
The hasAttribute is an Element method that returns true if the element has the specified arguments, false otherwise.

JavaScript

const imgs = document.getElementsByTagName('img');

Array.from(imgs).forEach(function(img){

    if(!img.hasAttribute('alt')){
        //Processing when there is no alt attribute
    }

});

Automatically add if img element does not have alt attribute

Use hasAttribute to determine if the alt attribute is present, otherwise add the alt attribute.

JavaScript

const imgs = document.getElementsByTagName('img');

Array.from(imgs).forEach(function(img){

    if(!img.hasAttribute('alt')){
        //Add alt attribute
        img.setAttribute('alt', '');
    }

});