Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select elements by attribute

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?

like image 550
Ciprian Grosu Avatar asked Oct 18 '22 01:10

Ciprian Grosu


People also ask

How can we select elements with a specified attribute in CSS?

[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.

How do you select all paragraph elements with a lang 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".


1 Answers

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
}
like image 369
Stefan Gehrig Avatar answered Oct 19 '22 13:10

Stefan Gehrig