Hi, I can check if an element have a specific attribute with:
if ($('#A').attr('myattr') !== undefined) {
// attribute exists
} else {
// attribute does not exist
}
How can I check if an element have any attribute?
Thank you
Hi, I can check if an element have a specific attribute with:
if ($('#A').attr('myattr') !== undefined) {
// attribute exists
} else {
// attribute does not exist
}
How can I check if an element have any attribute?
Thank you
If you want to see if the element has a particular attribute, just do this:
if ($('#something').is('[attribute]')) {
// ...
}
You'd need to use information from http://stackoverflow.com/questions/2048720/get-all-attributes-from-a-html-element-with-javascript-jquery
Not a whole jQuery code but it will work
$("a").click(
function () {
if($("a").get(0).attributes > 0)
alert("it has attributes");
})
Here's a function that determines whether any of the elements matching a selector have at least one attribute:
function hasOneOrMoreAttributes(selector) {
var hasAttribute = false;
$(selector).each(function(index, element) {
if (element.attributes.length > 0) {
hasAttribute = true;
return false; // breaks out of the each once we find an attribute
}
});
return hasAttribute;
}
Usage:
if (hasOneOrMoreAttributes('.someClass')) {
// Do something
}
If you want to operate on selected elements that have at least one attribute, it's even easier - you create a custom filter:
// Works on the latest versions of Firefox, IE, Safari, and Chrome
// But not IE 6 (for reasons I don't understand)
jQuery.expr[':'].hasAttributes = function(elem) {
return elem.attributes.length;
};
Which you can use like this:
$(document).ready(function(){
$('li:hasAttributes').addClass('superImportant');
}