I need to add aria-label to all links on the website using the link text as aria label

Viewed 428

I am trying to add aria-label to all links that don't have it on the site. I want to use the link text as aria-label.

$(document).ready(function () {
  $("a").each(function () {
    var attr = $(this).attr('aria-label');
    if (typeof attr == typeof undefined && attr == false) {
      var txt = $(this).text();
      $(this).attr("aria-label", txt);
    }
  });
});

2 Answers

The simplest way to do this would be to use the :not selector to find the elements without the attribute. Then you can provide a function to attr() which adds it to those found. Try this:

jQuery($ => {
  $('a:not([aria-label])').attr('aria-label', function() {
    return this.textContent.trim();
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#foo">Foo Bar</a>
<a href="#fizz" aria-label="I already have a label, leave me alone">Fizz Buzz</a>

Use This:

$("a").each(function () {
   var attr = $(this).attr('aria-label');
   if (!attr) {
    var txt = $(this).text();
    $(this).attr("aria-label", txt);
   }
});
Related