0

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?

5
  • What did you intend to test with the second if statement? That condition is never going to be true, because attr(x, y) returns a jQuery object, and objects are truthy, and so the negation is always false. Commented May 13, 2024 at 18:25
  • Secondly, have you waited for the document to load before searching for img elements? Commented May 13, 2024 at 18:30
  • I suspect you mean if ($(this).attr('alt') != 'Blog Image'). .attr('alt', 'Blog Image') sets the attribute, it doesn't compare the attribute. Commented May 13, 2024 at 18:36
  • What's the point of the first loop? A nonexistent alt attribute is the same as an empty string. Commented May 13, 2024 at 18:39
  • Answer to question one: find any image on a page that doesn't have an alt attribute at all, eg: <img src="..."> and add an empty one like <img src="..." alt=""> Answer to question two: So are you saying I need to wrap the code in a document.ready statement? My Jquery is REALLY rusty. Answer to question three: find all images with the alt text of "Blog Image" and replace them with an empty alt like so: change <img src="..." alt="Blog Image"> to <img src="..." alt=""> Commented May 14, 2024 at 0:39

1 Answer 1

0

<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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.