-3

I am trying to set atribute to all images. Now I have something like this:

function init(){
    imgs = document.images;
   for(i=0;i<imgs.length;i++){
      imgs[i].alt="test";
   }
}

but now I am replace all alts. How to add an attribute only to images that don't have it?

Giacomo
  • 341
  • 2
  • 8
  • 25
  • 3
    What have you tried...? Why not just test the value of `alt` before applying the new value? You should also avoid accessing and setting *attribute* values as properties, as the behavior is not consistent across browsers - see [What is the difference between properties and attributes in HTML?](https://stackoverflow.com/questions/6003819/what-is-the-difference-between-properties-and-attributes-in-html) – esqew Aug 12 '21 at 13:39

3 Answers3

2

This will replace the alt attributes of all images with no alt atttribute or the alt attribute set to an empty string:

function init(){
   imgs = document.images;
   for(i=0;i<imgs.length;i++){
      if (!imgs[i].alt){
        imgs[i].alt="test";
      }
   }
}
1

You can check if the images have an attribute using the getAttribute() method:

init();

function init(){
    imgs = document.images;
   for(i=0;i<imgs.length;i++){
   
      console.log(imgs[i].getAttribute("alt"));
   
     // Here check
      if (imgs[i].getAttribute("alt") === null) {
        imgs[i].alt="test";
      }
   }
}
<img alt="hello">
<img alt="hello">
<img>
AlexSp3
  • 2,201
  • 2
  • 7
  • 24
1

You can achive this by checking if given element has alt attribute.

function init()
{ 
   imgs = document.images;
   for(i=0;i<imgs.length;i++) { 
        if (imgs[i].hasAttribute("alt")) {
            continue;
        }
        imgs[i].alt="test"; 
    } 
}
TDiblik
  • 522
  • 4
  • 18