I am not sure if there is a function to achieve this but you can “cheat” by looking for the “alt=” text within a variable which contains the html of the img.
Try this out:
$('img').each(function(){
$(this).wrap('<span></span>');
var html = $(this).parent().html();
var alt = html.match( /alt=/ );
if(alt==null) {
alert('THERE IS NO ALT ATTRIBUTE');
} else {
if($(this).attr('alt')) {
alert('ALT ATTRIBUTE IS FILLED! yay!');
} else {
alert('ALT ATTRIBUTE IS EMPTY');
}
}
});
I like your thinking - that certainly works (tried it, tested it), but if there is a more refined way to do I’d still like to hear. For now, though, this works ver nicely
I would use getAttribute if it was ‘roll-my-own’ JavaScript, but I tried that and it didn’t work (most likely it was a scoping issue - as in it didn’t know what ‘this’ is).
Anyway, not to worry, I have a working solution for now
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
jQuery(function($){
$("body").append($("<ul>"));
$("img").each(function(){
var $this = $(this), text = "";
if (this.hasAttribute("alt") === false)
text = " has no alt attribute";
else if ($this.attr("alt") === "")
text = " has an empty alt attribute";
else
text = " has an alt attribute of '"+$this.attr("alt")+"'";
$("<li>").text($this.attr("id")+text).appendTo($("ul"));
});
});
</script>
</head>
<body>
<img id="test_alt" alt="test" />
<img id="no_alt" />
<img id="empty_alt" alt="" />
</body>
</html>