I am using a theme builder for WordPress and I’ve created some panels with an image and a bit of text in each. However, using the theme’s builder tools does not allow me to add aria labels to the images. So I’m trying to add aria labels to the images using javascript, but I just can’t seem to get this figured out. Can anyone help with this?
Here’s my HTML:
<div class="module module-link-block tb_c1o1565 icon-center solid licences-permits" data-lazy="1"><a href="#" title="Licences & Permits" class="tb_link_block_container ui tb_default_color"><img loading="lazy" width="66" height="66" decoding="async" class="tf_vmiddle tf_box tb_link_block_img" src="https://xxxxx.xxxxx.xxxxxx.net/wp-content/uploads/2024/04/licence-1.svg"><div class="tf-lb-content"><div class="tb_link_block_heading">Licences & Permits</div><div class="tb_link_block_blurb">Browse Licenses & Permits</div></div></a></div>
And here’s the javascript I’ve got so far… but it isn’t adding the aria label to the image img scr.
jQuery(function($) {
jQuery('.licences-permits').attr('aria-label','Licences & Permits');
});
</script>```
2
Answers
The issue is that you’re not actually targeting the
<img>
.Also not sure if you’re enqueuing your script correctly or if you always want the
aria-label
to be the same. I’d take a slightly different approach.This way you’re not hard coding the ARIA label to just one string but rather giving yourself the flexibility to have it modified based on what you put in the
<a>
title attribute.First of all, you shouldn’t try to add aria-label, but rather alt instead.
The alt attribute is mandatory for images, and must not be empty when the image is alone inside an interactive element such as link or button, what is the case here. The alt must be non-empty because otherwise, there is no accessible name to be spoken, rendered in braille, etc. when reaching the link, and therefore a screen reader user won’t know what it does.
You can also add an aria-label to the link (warning: not the image!), but image alt is universally supported everywhere, and by the first rule of ARIA, you should only use ARIA when there is no better solution.
Secondly, if possible, it would be better to add the alt attribute directly in the HTML. There should be no need for JavaScript to do that.
Now specifically to your script, you are targeting one of the div, not the image itself.
Additionally, is JQuery really needed ?
The code below should fix your problem and you don’t need JQuery to run it.