Search code examples
jqueryalt-attribute

Jquery find and replace an attribute not working


I'm trying to fix some accessibility errors in a new wordpress site by fixing alt tags. I created a new js file called "fixes.js" and included the following:

$('body img').each(function() {
    if ( ! $(this).attr('alt'))
        $(this).attr('alt', '');
});

$('body img').each(function() {
    if ( ! $(this).attr('alt', 'Blog Image'))
        $(this).attr('alt', '');
});

I can see the file is being loaded into the page, but it's not doing it's job, as you can see here:

https://axxs.io/articles/

Any ideas what the issue is?


Solution

  • <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function() {
            // Find images without an alt attribute and add a blank alt attribute
            $('body img:not([alt])').attr('alt', '');
    
            // Find images with alt attribute equal to "Blog Image" and replace with a blank alt attribute
            $('body img[alt="Blog Image"]').attr('alt', '');
        });
    </script>