jQuery: check if an attribute exists

jQuery doesn't provide a method similar to hasAttribute() to determine whether a given attribute exists in the DOM. However, we can use the attr() method for this task. In fact, this method returns a boolean value when used with conditional statements.

We can create the hasAttr() method:

(function($) {

	$.fn.hasAttr = function(attr) {
	
		attr = attr || 'class';
	
		var that = this;
		
		if(!that.attr(attr)) {
		
			return false;
		
		}
		
		return true;
	
	};

})(jQuery);

In this case, as for attr(), we should not return this. An example:

<p id="one">Test</p>
<p>Test</p>
<p title="two">Test</p>

We can run the following test:

$(function() {

	$('p').each(function() {
	
		var $p = $(this);
		
		console.log($p.hasAttr('id'));
		console.log($p.hasAttr('title'));
		
	});
});

which outputs the following:

true
false
false
false
false
true

Comments are closed.