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?

Martin G
  • 17,357
  • 9
  • 82
  • 98
Ciprian Grosu
  • 2,821
  • 3
  • 20
  • 14
  • 2
    As an aside, an 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 08 '09 at 11:46
  • http://stackoverflow.com/questions/1318076/jquery-hasattr-checking-to-see-if-there-is-an-attribute-on-an-element – kulekci Oct 10 '10 at 08:51
  • 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 09 '15 at 20:06

17 Answers17

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
}
Stefan Gehrig
  • 82,642
  • 24
  • 155
  • 189
  • 3
    Not a great answer. "undefined" is not a keyword in Javascript. See http://constc.blogspot.com/2008/07/undeclared-undefined-null-in-javascript.html – mhenry1384 Apr 04 '11 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. – Stefan Gehrig Apr 05 '11 at 06:52
  • 6
    Doesn't work if the attribute have an empty string. An example is myattr='' – mythicalprogrammer Sep 26 '11 at 16:39
  • Not a good answer, what if myattr == 0? For example, selectedIndex. (.prop() is now used for this, but i think it's still a valid example). – bmarti44 May 16 '12 at 22:25
  • @mhenry - I would consider redefining undefined to be the coding error, not the usage of undefined after someone redefined it. – Jimbo Jonny Nov 14 '12 at 19:14
  • @JimboJonny I would redefine it just to teach you a lesson about not making assumptions about the global namespace. ;-) – mhenry1384 Nov 16 '12 at 02:12
  • 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 :) – Jimbo Jonny Nov 20 '12 at 15:58
  • One solution is to explicitly [not] define `undefined` in your current scope: `(function() { var undefined; if(... !== undefined) { ... } })();`. Of course, comparing `typeof` with the string "undefined" is arguably easier. Albeit, it's verbose, so I prefer to write a function wrapper for me. `MyNamespace.defined(arg)`. Note that `typeof` can misbehave in IE... – bambams Jul 29 '13 at 15:28
  • 8
    if (typeof $('#A').attr('myattr') !== 'undefined') – James Westgate Apr 09 '14 at 14:11
  • One can use `void 0` in place of `undefined`, to avoid the problem of `undefined` not being a keyword. – Brian M. Hunt Sep 19 '14 at 12:34
192

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

$(":checkbox[myattr]")
cletus
  • 616,129
  • 168
  • 910
  • 942
  • 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 '11 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 '11 at 17:27
  • 1
    It throws js errors if you try something like :td[myattr]. So I think this feature was specifically targeting checkboxes. – fooledbyprimes Aug 29 '12 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 '12 at 05: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 '14 at 09: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

Jonathan Bergeron
  • 1,864
  • 2
  • 13
  • 15
  • 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 01 '13 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. – Jonathan Bergeron Apr 10 '13 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 '13 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")); – Daniel Howard May 14 '13 at 07: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 '15 at 00:51
10

This will work:

$('#A')[0].hasAttribute('myattr');
powermikee
  • 109
  • 1
  • 4
  • 2
    see link: http://stackoverflow.com/questions/1318076/jquery-hasattr-checking-to-see-if-there-is-an-attribute-on-an-element – RetroCoder Jun 16 '14 at 21:09
  • @RetroCoder, what's your point about your link? This test seems quite good, especially because often you use `$(this).` when here you can do `this.hasAttribute('...')` directly (and do not care about older browsers, of course.) – Alexis Wilke Aug 05 '14 at 02: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.

bambams
  • 745
  • 1
  • 8
  • 18
  • 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 '11 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 '13 at 15:14
6

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

Cᴏʀʏ
  • 105,112
  • 20
  • 162
  • 194
ssps
  • 61
  • 1
  • 1
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.

Daved
  • 2,082
  • 1
  • 18
  • 23
2
if (!$("#element").attr('my_attr')){
  //return false
  //attribute doesn't exists
}
Fury
  • 4,643
  • 5
  • 50
  • 80
  • 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 '14 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+']');
}
dhc
  • 647
  • 8
  • 17
1
$("input#A").attr("myattr") == null
Mathias F
  • 15,906
  • 22
  • 89
  • 159
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') ) { ...

AaronLS
  • 37,329
  • 20
  • 143
  • 202
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
    }
});
as-if-i-code
  • 2,103
  • 1
  • 10
  • 19
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.

Shoter
  • 976
  • 11
  • 23
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)
}
ErnestV
  • 117
  • 1
  • 6
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);

})
Merbin Joe
  • 611
  • 6
  • 27
0

simply:

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

more info: official docs

Kambiz
  • 1,217
  • 9
  • 8
  • 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. – Jimbo Jonny Nov 14 '12 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");
zach
  • 346
  • 2
  • 9
  • 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 03 '12 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 '12 at 09: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. – Jimbo Jonny Nov 14 '12 at 19:21