Ciprian Grosu
Ciprian Grosu

Reputation: 2831

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?

Upvotes: 254

Views: 260926

Answers (17)

Kambiz
Kambiz

Reputation: 1217

simply:

$("input[name*='value']")

more info: official docs

Upvotes: 0

Merbin Joe
Merbin Joe

Reputation: 688

We can easy to access the value attribute value if the attribute present in the given HTML element.

var offORonlinePath="../img/";   //We can easy to change the path anytime
var extension=".webp"; //we can later change any value like png,jpg,...

$("img[data-src]").each(function(){
  var imgName=$(this).data("src");

  $(this).attr("src",offORonlinePath+imgName+extension);

})

Upvotes: 0

as-if-i-code
as-if-i-code

Reputation: 2340

To get collection of all checkbox elements based on multiple attributes, e.g. in this case id and myattr:

var checkboxCollection = $(":checkbox[id][myattr]");

If you need to assign event handler to each checkbox in collection:

$(":checkbox[id][myattr]").change(function() {
    if(this.checked) {
        var valueOfAttribute = $(this).attr('myattr');
        // code here
    }
    else{
        // code here
    }
});

Upvotes: 1

ErnestV
ErnestV

Reputation: 137

To select elements having a certain attribute, see the answers above.

To determine if a given jQuery element has a specific attribute I'm using a small plugin that returns true if the first element in ajQuery collection has this attribute:

/** hasAttr
 ** helper plugin returning boolean if the first element of the collection has a certain attribute
 **/
$.fn.hasAttr = function(attr) {
   return 0 < this.length
       && 'undefined' !== typeof attr
       && undefined !== attr
       && this[0].hasAttribute(attr)
}

Upvotes: 0

dhc
dhc

Reputation: 657

as in this post, using .is and the attribute selector [], you can easily add a function (or prototype):

function hasAttr($sel,attr) {
    return $sel.is('['+attr+']');
}

Upvotes: 2

Shoter
Shoter

Reputation: 1039

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.

Upvotes: 0

powermikee
powermikee

Reputation: 109

This will work:

$('#A')[0].hasAttribute('myattr');

Upvotes: 10

Fury
Fury

Reputation: 4776

if (!$("#element").attr('my_attr')){
  //return false
  //attribute doesn't exists
}

Upvotes: 2

Jonathan Bergeron
Jonathan Bergeron

Reputation: 1866

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

Upvotes: 166

AaronLS
AaronLS

Reputation: 38367

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

Upvotes: 1

ssps
ssps

Reputation: 61

$("input[attr]").length might be a better option.

Upvotes: 6

Daved
Daved

Reputation: 2082

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.

Upvotes: 4

zach
zach

Reputation: 356

JQuery will return the attribute as a string. Therefore you can check the length of that string to determine if is set:

if ($("input#A").attr("myattr").length == 0)
 return null;
else
 return $("input#A").attr("myattr");

Upvotes: -5

bambams
bambams

Reputation: 765

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.

Upvotes: 8

Stefan Gehrig
Stefan Gehrig

Reputation: 83622

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
}

Upvotes: 371

Mathias F
Mathias F

Reputation: 15891

$("input#A").attr("myattr") == null

Upvotes: 1

cletus
cletus

Reputation: 625007

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

$(":checkbox[myattr]")

Upvotes: 192

Related Questions