0

Ok so im using hubspot for inbound marketing and the have a thing called page grader that finds errors in your page. The most common warning is page has images without alt text. Since im dealing with a really big drupal site and dont want to go through every image and set an alt I would rather just have a JQuery script run check if it has alt if not add some plain default.

I have the easy part with setting the alt attribute
$(img).attr('alt', 'some text');

but Im not sure how to loop and find images that dont have alts because if they do have one set it is obviously going to be more relevant to search engines as well as people with disabilities who use the alt tags.

3
Contributors
4
Replies
10
Views
7 Years
Discussion Span
Last Post by marta.johnsson
0

Try using the :not() selector.

$("img:not([alt])").attr("alt", "some text");
0

That did not work for me I made a document with an image with a set alt and one thats not. This is the code I am trying to alter right now.

$(document).ready(function(){
				var altText;
				altText = $('img.this').getAttribute('alt');
				if ( altText == ""){
					$('img.this').attr('alt','some text');
				}
			 });
0

The code I posted worked fine for me.
It works when the img tag has no alt attribute specified at all. But if the alt attribute is specified but is set to empty string, then yes, the above code fails.

Try the following:

$("img").each(function() {
    var img = $(this);
    if (!img.attr("alt") || img.attr("alt") == "")
        img.attr("alt", "some text");
    });
});
0

What if you try to add ! before your second condition?

$("img").each(function() {
    var img = $(this);
    if (!img.attr("alt") || img.attr("alt") === "")
        img.attr("alt", "some text");
    });
});

Edited by marta.johnsson: it wasn't logic

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.