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']");

Comments

  1. User Avatar
    Dmitry

    Looks like an extra typeof is in if condition of first code block. Shouldn’t it be : if(typeof attr !== ‘undefined’ && attr !== false) … ?

    • User Avatar
      Tim
      Permalink to comment#

      The first typeof applies to the attr, the second typeof applies to undefined. But more importantly, I was wondering if it could be shortened to:

      var attr = $(this).attr(‘name’);

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

      or

      if (attr) {
      // Element has this attribute
      }

      I think testing for if (attr) would identify whether attr was undefined would it not?

      Tim

  2. User Avatar
    Ralph
    Permalink to comment#

    Not sure if I’m missing something, but what about this?

    if ($(this).is('[name]')) {
    // Element has this attribute
    }

Submit a Comment

Posting Code

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.

icon-anchoricon-closeicon-emailicon-linkicon-logo-staricon-menuicon-nav-guideicon-searchicon-staricon-tag