Check and insert alt attribute for images that skip it
I want to write a Java tool to evaluate HTML pages of an existing site, and if any image does not have an alt attribute, the tool will insert alt = "" into that image. One approach is to use an HTML parser (like HtmlCleaner) to create the DOM and then add the alt attribute to the images in the DOM before writing the HTML.
However, this approach will not keep the original HTML intact and is likely to cause some unpredictable side effects, especially. when the existing number of HTML pages is huge and there is no guarantee that they will be well formed.
Is there a safer way to accomplish this (i.e. keep the original HTML intact and only add the alt attribute)?
a source to share
Unless you write some awful mess of regex or other string manipulation code, I don't believe there is any other way to do this.
I am wondering why you want to do this? The only reason I can imagine is to go through some kind of automatic validation, but the reason the alt tags are required is a usability issue. Adding empty alt tags doesn't help in any way. You are just hiding the problem.
Instead, I would suggest writing some Javascript that throws a red border around any image that is not in the alt tag and makes the foreground designers add meaningful alt tags to each image that is marked this way.
a source to share
It seems pointless to add empty alt tags to your layout. I'm second to Chris in that he defeats the goal of having alt tags in the first place, and I agree with David Dorward's comment.
But, if there is some ulterior motive here, you can do it after the fact in the browser with javascript (or preferably jQuery). The client browser, of course, will not be able to modify the original HTML and is smart enough to parse it, even if it is not well-formed.
Using jQuery, place this script in the chapter section of your page:
<script language="javscript">
$(function() {
$('img:not([alt])').attr('alt','');
});
</script>
And make sure you include jQuery library .
a source to share
I have used the Jericho HTML Parser library in the past with success to parse HTML. It should work well with poorly formed HTML. This might change the original HTML.
a source to share