jQuery hasAttr Option

So on searching for the elusive hasAttr function in jQuery (which doesn’t exist if you were wondering) I found all the usual !== undefined answers and then thought – We already have a function for this! Just not a simple direct function.

The solution I propose is thus:

$(element).filter("[attrName]").length > 0;

Simple huh? And if you want to extend jQuery then you can use the following:

$.fn.hasAttr = function(attr){
    return this.filter("[" + attr + "]").length > 0;
}

It will allways work, but the logic for more than one element will be if any one of the elements has the attribute. If you want an allHasAttr function it would go as follows:

$.fn.allHaveAttr = function(attr){
    return this.filter("[" + attr + "]").length == this.length;
}

About Simeon Cheeseman

I enjoy a wide variety of computer and board games, have a BSc in Computer Science and have played percussion for 18 years.

Posted on August 3, 2012, in Javascript, jQuery and tagged , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: