Checking Attribute Status with JQuery

04/24/2013, Wed
Categories: #JavaScript
Tags: #jQuery

Get Element's Attribute Value or Status

With JQuery, you can do this $('#your-element').hasClass('a-class') to check if the element has a certain class. The problem is that you have to know the class name ahead of time when you use .hasClass. I wanted a general way to know if the class attribute actually exists on the element, so I created the getAttrStat function for JQuery to see if the attribute in question on the element is undefined, empty, or has a value without knowing the attribute value ahead of time.

// Function to Get Attribute Status

// the return codes are arbitrary
function getAttrStat(elem, attr) {
  var attrValue = null,
    attrStatus = (attrValue = elem.attr(attr)) || 0;
  if (attrStatus === 0) {
    if (attrValue === "") {
      // attr is empty
      console.log(elem.selector + " '" + attr + "' is empty.");
      return 1;
    } else if (typeof attrValue == "undefined")
      // attr is undefined
      console.log(elem.selector + " '" + attr + "' is undefined.");
    return 0;
  } else {
    // attr has a value
    console.log(elem.selector + " '" + attr + "' has a value: " + attrValue);
    return 2;
  }
}
// Usage of Function

// returns 0 and logs #a-id 'class' is undefined.
getAttrStat($("#a-id"), "class");

// returns 1 and logs #b-id 'class' is undefined.
getAttrStat($("#b-id"), "class");

// returns 2 and logs #c-id 'class' is undefined.
getAttrStat($("#c-id"), "class");
<!-- Divs with Attributes -->

<div id="a-id"></div>
<div class="" id="b-id"></div>
<div class="c-class" id="c-id"></div>

Demo