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...



Filter the selection




  1. User Avatar

    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
      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


      if (attr) {
      // Element has this attribute

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


  2. User Avatar
    Permalink to comment#

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

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

  3. User Avatar
    Permalink to comment#

    Hello. If you don’t put “undefined” in quotes it doesn’t work for Chrome.

Leave 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.