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?
This question is related to
jquery
attributes
This will work:
$('#A')[0].hasAttribute('myattr');
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
}
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.
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.
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)
}
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') ) { ...
if (!$("#element").attr('my_attr')){
//return false
//attribute doesn't exists
}
$("input[attr]").length
might be a better option.
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");
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+']');
}
$("input#A").attr("myattr") == null
Source: Stackoverflow.com