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?
[attribute] Selector: This type of attribute selector is used to select all the elements that have the specified attribute and applies the CSS property to that attribute. For example the selector [class] will select all the elements with the style attribute.
p[lang] − Selects all paragraph elements with a lang attribute. p[lang="fr"] − Selects all paragraph elements whose lang attribute has a value of exactly "fr". p[lang~="fr"] − Selects all paragraph elements whose lang attribute contains the word "fr".
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With