253

I have a collection of checkboxes with generated ids and some of them have an extra attribute. Is it possible to use JQuery to check if an element has a specific attribute? For example, can I verify if the following element has the attribute "myattr"? The value of the attribute can vary.

<input type="checkbox" id="A" myattr="val_attr">A</input>

For example how can I get a collection of all checkboxes that have this attribute without checking one by one? Is this possible?

3
  • 2
    As an aside, an <input/> is an empty tag that isn't meant to have content inside of it. Perhaps you're not concerned with validating seeing as you have myatttr present...
    – ScottE
    Jul 8, 2009 at 11:46
  • If you already have a collection and you want to filter out only elements with specific attribute - just do it - $filtered = $collection.filter('[attribute_name]');
    – jave.web
    Jul 9, 2015 at 20:06

17 Answers 17

370
if ($('#A').attr('myattr')) {
    // attribute exists
} else {
    // attribute does not exist
}

EDIT:

The above will fall into the else-branch when myattr exists but is an empty string or "0". If that's a problem you should explicitly test on undefined:

if ($('#A').attr('myattr') !== undefined) {
    // attribute exists
} else {
    // attribute does not exist
}
10
  • 3
    Not a great answer. "undefined" is not a keyword in Javascript. See constc.blogspot.com/2008/07/…
    – mhenry1384
    Apr 4, 2011 at 22:51
  • 16
    You're right... But redefining undefined is considered an edge case and the comparison above will work in 99% of all cases. Apr 5, 2011 at 6:52
  • 6
    Doesn't work if the attribute have an empty string. An example is myattr='' Sep 26, 2011 at 16:39
  • 3
    @mhenry - then you'd be in error :) If you were building the project for me or alongside me, I'd require you to fix your error. If it were an open source package then I (along with many users) would stop using it based on the grounds that it was poorly coded. If you didn't change it then someone else would eventually fork a version without the error and people would use that instead, and you'd lose your own project, as has happened many times before when someone creates a package that's a good idea with poor implementation. Either way it would teach you a lesson about coding practices :) Nov 20, 2012 at 15:58
  • 8
    if (typeof $('#A').attr('myattr') !== 'undefined') Apr 9, 2014 at 14:11
192

Do you mean can you select them? If so, then yes:

$(":checkbox[myattr]")
5
  • 4
    Note that if you're testing for existence (presumably in an if statement, for example) it's probably more correct/reliable to do: if($(":checkbox[myattr]").length()>0)...
    – rinogo
    Aug 15, 2011 at 21:18
  • 14
    @rinogo: actually all you need is if($(":checkbox[myattr]").length) . The () after length is not necessary, neither is the > 0, 0 evaluates to false in equality tests that do not require strict equality (both value and type).
    – bmarti44
    Aug 23, 2011 at 17:27
  • 1
    It throws js errors if you try something like :td[myattr]. So I think this feature was specifically targeting checkboxes. Aug 29, 2012 at 14:48
  • 6
    The colon selects pseudo-classes, determined by the type attr. To apply the same thing to td's, just omit the colon.
    – dhochee
    Dec 22, 2012 at 5:51
  • Or if you wanted to see if something didn't have an attribute such as find all links that don't have href attributes. $("#myBox").find('a').filter(':not([href])')
    – timbrown
    Jul 25, 2014 at 9:16
166

I know it's been a long time since the question was asked, but I found the check to be clearer like this :

if ($("#A").is('[myattr]')) {
    // attribute exists
} else {
    // attribute does not exist
}

(As found on this site here)

Documentation about is can be found here

5
  • According to the W3C, boolean attributes are defined by presence or absence of the attribute. jQuery provides the method .attr() to manipulate attribute values. But how do we add an attribute without value ? The method you provide to test the presence of an attribute is not described in the jQuery documentation (1.8.2). Do you know how to add an attribute with jQuery ?
    – chmike
    Mar 1, 2013 at 16:53
  • @chmike To add an attribute, I'd do it this way : $("#A").prop("myNewAttribute", someValue); You can give someValue any value of your choice : string, number, empty string, true/false. Apr 10, 2013 at 12:34
  • This will add the attribute with an assigned value which is not the same as an attribute without value.
    – chmike
    Apr 11, 2013 at 13:18
  • 5
    I agree, this is the best answer (using jQuery) - very clear and concise. I did find myself wondering why jQuery doesn't just have a hasAttribute() function, and the answer is, that native javascript already has one. Any HTML Dom Element has a method hasAttribute('attributeName'). So you could do: $('#A')[0].hasAttribute('myattr') @chmike - I don't think you can add an empty attribute using jQuery functions, but you can do it with the HTML Dom Element object in a similar way as follows: $("#A")[0].setAttributeNode(document.createAttribute("myNewAttribute")); May 14, 2013 at 7:23
  • 1
    Just a comment that I like this answer, but was confused about the comments asking how to add an attribute without a value. These aren't related to the question or the answer.
    – goodeye
    Feb 17, 2015 at 0:51
10

This will work:

$('#A')[0].hasAttribute('myattr');
2
  • 2
    see link: stackoverflow.com/questions/1318076/…
    – RetroCoder
    Jun 16, 2014 at 21:09
  • @RetroCoder, what's your point about your link? This test seems quite good, especially because often you use $(this).<something> when here you can do this.hasAttribute('...') directly (and do not care about older browsers, of course.) Aug 5, 2014 at 2:01
8

In JavaScript,...

null == undefined

...returns true*. It's the difference between == and ===. Also, the name undefined can be defined (it's not a keyword like null is) so you're better off checking some other way. The most reliable way is probably to compare the return value of the typeof operator.

typeof o == "undefined"

Nevertheless, comparing to null should work in this case.

* Assuming undefined is in fact undefined.

2
  • Undefined is not a reserved keyword in JavaScript. In jQuery it is possible munging its name exactly because it is constructed with the "var" contructor and not valued. On the top of the magic library code, infact, there's a line which states "var undefined;" and this way an undefined variable is defined with that name in the jQuery scope... But it could all the same be named "unnamed" by typing "var unnamed;"
    – yodabar
    Jan 19, 2011 at 22:57
  • 1
    This not check for a attribute, this check for a property in a javascript object why this have 6 upvotes?
    – ncubica
    Jul 23, 2013 at 15:14
6

$("input[attr]").length might be a better option.

4

A couple ideas were tossed around using "typeof", jQuery ".is" and ".filter" so I thought I would post up a quick perf compare of them. The typeof appears to be the best choice for this. While the others will work, there appears to be a clear performance difference when invoking the jq library for this effort.

2
if (!$("#element").attr('my_attr')){
  //return false
  //attribute doesn't exists
}
1
  • 1
    this probably wont work, since you can add an attribute with no value. in such case, this condition will pass, although the desired behavior could be to return true, the attribute is set. similar to PHPs isset() or for example in js $("#element").attr('my_attr') === false,
    – ulkas
    Jul 22, 2014 at 12:22
2

as in this post, using .is and the attribute selector [], you can easily add a function (or prototype):

function hasAttr($sel,attr) {
    return $sel.is('['+attr+']');
}
1
$("input#A").attr("myattr") == null
3
  • 1
    $().attr() will not return null as suggested by our example, instead it'll return undefined. Jul 8, 2009 at 11:48
  • Works for me in firebug, but that may be an firebug thing
    – Mathias F
    Jul 8, 2009 at 12:17
  • Haven't tried it, but that's what the documentation says: docs.jquery.com/Attributes/attr#name Jul 8, 2009 at 12:23
1

In addition to selecting all elements with an attribute $('[someAttribute]') or $('input[someAttribute]') you can also use a function for doing boolean checks on an object such as in a click handler:

if(! this.hasAttribute('myattr') ) { ...

1

To get collection of all checkbox elements based on multiple attributes, e.g. in this case id and myattr:

var checkboxCollection = $(":checkbox[id][myattr]");

If you need to assign event handler to each checkbox in collection:

$(":checkbox[id][myattr]").change(function() {
    if(this.checked) {
        var valueOfAttribute = $(this).attr('myattr');
        // code here
    }
    else{
        // code here
    }
});
0

I have created npm package with intended behaviour as described above in question.

Link to [npm] and [github]

Usage is very simple. For example:

<p id="test" class="test">something</p>
$("#test").hasAttr("class")

returns true.

Works with camelcase too.

0

To select elements having a certain attribute, see the answers above.

To determine if a given jQuery element has a specific attribute I'm using a small plugin that returns true if the first element in ajQuery collection has this attribute:

/** hasAttr
 ** helper plugin returning boolean if the first element of the collection has a certain attribute
 **/
$.fn.hasAttr = function(attr) {
   return 0 < this.length
       && 'undefined' !== typeof attr
       && undefined !== attr
       && this[0].hasAttribute(attr)
}
0

We can easy to access the value attribute value if the attribute present in the given HTML element.

var offORonlinePath="../img/";   //We can easy to change the path anytime
var extension=".webp"; //we can later change any value like png,jpg,...

$("img[data-src]").each(function(){
  var imgName=$(this).data("src");

  $(this).attr("src",offORonlinePath+imgName+extension);

})
0

simply:

$("input[name*='value']")

more info: official docs

1
  • 1
    Unescaped double quotes within the string defined with double quotes, not a valid string. Unfortunately I can't edit it for you because an edit has to change 6 characters or more, needs to be changed though. Nov 14, 2012 at 19:18
-5

JQuery will return the attribute as a string. Therefore you can check the length of that string to determine if is set:

if ($("input#A").attr("myattr").length == 0)
 return null;
else
 return $("input#A").attr("myattr");
3
  • So, I know it has been over a year and I should have addressed it long ago. I am curious about what part didn't work? If I knew you were just trying to select them I wouldn't have given the above code. I thought you wanted to check them individually. JQuery does in fact return the attribute as a string and you can check the length of that string just as any other string. So as long as your selector and attribute were correct you should have been able to test to see if a particular input had that attribute. Anyway, I just didn't want people to discount the principle because it does work.
    – zach
    Jan 3, 2012 at 17:14
  • 6
    it will fail in the case where the attribute is not present in which case $("input#A").attr("myattr") return undefined rather than a string and undefined.length will fail
    – Rune FS
    Apr 17, 2012 at 9:57
  • Only detects an empty attribute vs. one with content, fails on a non-existing attribute. The original question was about detecting existence of the attribute, making this a failure as an answer to the question. Nov 14, 2012 at 19:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.