skip to Main Content
<img src="first.jpg" alt="first" width="500" height="600" />
<img src="second.jpg" alt width="500" height="600" />
<img src="third.jpg" alt="third" width="500" height="600" />
<img src="fourth.jpg" alt width="500" height="600" />
<img src="fifth.jpg" alt="" width="500" height="600" />

find image tags with alt attribute without double quotes and replace with empty double quotes for ADA accessibility, I need to jquery to find second and fourth img tags replace with alt="" just like fifth. This is sample html markup, a page can have this instances 10 or 20 instances, all these should be replaced with alt=""

I tried this below didn’t work

$(function() {
  $("img").each(function() {
    if (this.alt) {
      console.log(this.alt);
    } else {
      $(this).attr('alt', "");
    }
  });
});

2

Answers


  1. The browser treats them the same way for accessibility purposes.

    If your goal is to ensure that all alt attributes are an empty string for ADA accessibility, then you don’t need to worry about whether they have quotes or not. The following jQuery code would suffice:

    $(function() {
      $("img").attr('alt', "");
    });
    

    This code will set the alt attribute of all <img> elements to an empty string, which is the desired outcome for accessibility.

    Login or Signup to reply.
  2. First of all <img alt> is equivalent to <img alt=""> or <img alt=''>, so what you are trying to do is useless. (You can check the console.log() value of the code snippet to understand it)

    Now I can see that you have used the first part of src as alt values. So why can’t you do the same for empty alt values? You can achieve it through jQuery easily.

    Working snippet:

    $(function() {
      $("img").each(function() {
        console.log($(this).attr('alt') =='' ? 'empty':$(this).attr('alt'));
        if (!$(this).attr('alt')) {
          $(this).prop('alt', $(this).attr('src').split(".")[0]);
        }
      });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <img src="first.jpg" alt="first" width="500" height="600" />
    <img src="second.jpg" alt width="500" height="600" />
    <img src="third.jpg" alt="third" width="500" height="600" />
    <img src="fourth.jpg" alt width="500" height="600" />
    <img src="fifth.jpg" alt="" width="500" height="600" />
    <img src="sixth.jpg" alt='' width="500" height="600" />

    Final output: https://prnt.sc/d7009eGbVprT

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search