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.

Try using the :not() selector.

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

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');
				}
			 });

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");
    });
});

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");
    });
});
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.