[jQuery] - how to identify missing vs empty attribute value

This may be a simple one, but maybe not …

In jQuery I have a function that is used to alert user to missing alt attributes:

var alt = $(this).attr("alt");
 if(alt==undefined) {

The thing is, that code (alt==undefined) is true for:

  • missing alt attribute
  • alt attribute present but empty, e.g. alt=“”

I’ve had a look through some jQuery resources and I cannot find what I’m after which is something like this:

if [B](alt exists)[/B] {
 if (alt="") {
 //alt is empty
 else {
 //alt has this value ...
else {
 //no alt present

So there are three scenarios I need to match, not just 2. Hope this makes sense … and that someone knows how I can achieve this using jQuery!

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:

   var html = $(this).parent().html();
   var alt = html.match( /alt=/ );
   if(alt==null) {
   } 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 :slight_smile:

Well the standard way is to use the getAttribute method
Then you can use code such as

alt = this.getAttribute('alt');
if (alt === null) {
    // not there
} else if (alt === '') {
    // empty
} else {
    // has value

Paul, your method doesn’t seem to work in IE7… :frowning:

<img />
<img alt="" />
<img alt="ss" />

 alt = this.getAttribute('alt');
 if (alt === null) {
  } else if (alt === '') {
  } else {

Each alert should come up once, but instead the “empty” alert is coming up twice and the “there” alert comes up once…

It works in Firefox and Opera.

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

		<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
		<script type="text/javascript">
					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";
						text = " has an alt attribute of '"+$this.attr("alt")+"'";
		<img id="test_alt" alt="test" />
		<img id="no_alt" />
		<img id="empty_alt" alt="" />

Yes IE7 has some special issues there. Salathe seems to have a nice solution.

Yes but Salathe’s doesn’t seem to work in IE7 either…

There are some interesting solutions discussed here: http://tobielangel.com/2007/1/11/attribute-nightmare-in-ie