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?
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') ) { ...
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,...
...returns
true
*. It's the difference between==
and===
. Also, the nameundefined
can be defined (it's not a keyword likenull
is) so you're better off checking some other way. The most reliable way is probably to compare the return value of thetypeof
operator.Nevertheless, comparing to null should work in this case.
* Assuming
undefined
is in fact undefined.I have created npm package with intended behaviour as described above in question.
Link to [npm] and [github]
Usage is very simple. For example:
returns true.
Works with camelcase too.
This will work: