Select elements by attribute

2019-01-02 19:39发布

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?

13条回答
十年一品温如言
2楼-- · 2019-01-02 20:00

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') ) { ...

查看更多
看淡一切
3楼-- · 2019-01-02 20:03
if (!$("#element").attr('my_attr')){
  //return false
  //attribute doesn't exists
}
查看更多
柔情千种
4楼-- · 2019-01-02 20:05

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.

查看更多
查无此人
5楼-- · 2019-01-02 20:07

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.

查看更多
君临天下
6楼-- · 2019-01-02 20:09

I have created npm package with intended behaviour as described above in question.

Link to [npm] and [github]

Usage is very simple. For example:

<p id="test" class="test">something</p>
$("#test").hasAttr("class")

returns true.

Works with camelcase too.

查看更多
ら面具成の殇う
7楼-- · 2019-01-02 20:11

This will work:

$('#A')[0].hasAttribute('myattr');
查看更多
登录 后发表回答