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?


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

$(":checkbox[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
}

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

链接地址: http://www.djcxy.com/p/83710.html

上一篇: 淘汰选择下拉禁用项目

下一篇: 按属性选择元素