Search code examples
javascriptwordpressaccessibilitywai-aria

Add aria-label to an image using javascript


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 &amp; 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 ?avascript 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>```

Solution

  • The issue is that you're not actually targeting the <img>.

    jQuery( function($) { 
        jQuery( '.licences-permits img.tb_link_block_img' ).attr( 'aria-label', 'Licences & Permits' ); 
     } );
    

    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.

    (function( $ ) {
        'use strict';
        $( document ).ready( function() {
            if( $( '.licences-permits' ).length > 0 ) {
                $( '.licences-permits' ).each( function() {
                    var newLabel = $( this ).children( 'a' ).attr( 'title' );
                    $( '.licences-permits img.tb_link_block_img' ).attr( 'aria-label', newLabel ); 
                } );
            }
        } );
    } )( jQuery );
    

    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.