Select elements by attribute
JqueryAttributesJquery Problem Overview
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?
Jquery Solutions
Solution 1 - Jquery
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
}
Solution 2 - Jquery
Do you mean can you select them? If so, then yes:
$(":checkbox[myattr]")
Solution 3 - Jquery
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
Solution 4 - Jquery
This will work:
$('#A')[0].hasAttribute('myattr');
Solution 5 - Jquery
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.
Solution 6 - Jquery
$("input[attr]").length
might be a better option.
Solution 7 - Jquery
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.
Solution 8 - Jquery
if (!$("#element").attr('my_attr')){
//return false
//attribute doesn't exists
}
Solution 9 - Jquery
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+']');
}
Solution 10 - Jquery
$("input#A").attr("myattr") == null
Solution 11 - Jquery
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') ) { ...
Solution 12 - Jquery
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
}
});
Solution 13 - Jquery
Solution 14 - Jquery
I have created npm package with intended behaviour as described above in question.
Usage is very simple. For example:
<p id="test" class="test">something</p>
$("#test").hasAttr("class")
returns true.
Works with camelcase too.
Solution 15 - Jquery
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)
}
Solution 16 - Jquery
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);
})
Solution 17 - Jquery
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");