Skip to main content
Home / Code Snippets / jQuery Code Snippets / A jQuery hasAttr() Equivalent

A jQuery hasAttr() Equivalent

jQuery doesn't really have an .hasAttr() function. You might assume that it does, but alas, it does not.

A StackOverflow thread has some pretty good solutions.

Get the attribute, check the value

var attr = $(this).attr('name');

// For some browsers, `attr` is undefined; for others, `attr` is false. Check for both.
if (typeof attr !== typeof undefined && attr !== false) {
  // Element has this attribute
}

Native JavaScript has a way

If you only have a jQuery reference...

$(this)[0].hasAttribute("name");

jQObject[0].hasAttribute("name");

Filter the selection

$(this).is('[name]');

$(this).filter("[name='choice']");
icon-link icon-logo-star icon-search icon-star