jQuery: check if an element has a given attribute with the .attr() method

jQuery: check if an element has a given attribute with the .attr() method

How to test if an element has a given attribute by using the jQuery's .attr() method.

The DOM specifications provide us with the hasAttribute() method which tests if a given element has a specific attribute. This method returns a boolean value indicating whether the current node has the attribute passed as argument. jQuery has the .attr() method which returns the attribute's value or undefined if the attribute is not present.

Having an element whose ID's value is test, we can run the following tests:


​console.log($('#test').attr('title'));​​​​​​​​​​​​​ // undefined
console.log($('#test').attr('id'));  // test

To test if an element has a given attribute in jQuery, you can do one of the following:


if(typeof $('#test').attr('title') === 'undefined') {

  // The element has no title attribute

}

if($('#test').attr('title') == 'undefined') {

	// The element has no title attribute

}

The former version is more accurate. It's worth mentioning that with this kind of jQuery's method the automatic casting performed by JavaScript with the undefined value (from undefined to false) can lead to inconsistent results.