Check if an element contains attribute or not using jquery

In this programming tutorial we will learn how to check if an element contains attribute or not using jquery. Using built-in jquery's function we can check if an element contains particular attribute or not but we cannot check if an element contains at least one attribute or not. So let's start

Check if an element contains attribute or not using jquery
function hasAtleastOneAttribute(selector) {
    var attributeExists = false;
    $(selector).each(function(index, element) {
        if (element.attributes.length > 0) {
            attributeExists = true;
            return false; // breaks out of the each once we find any attribute
        }
    });
    return attributeExists;
}

Let's have a look over how to call it.
if (hasAtleastOneAttribute('.myClass')) {
    // Write your stuff here
}

So that's it.
I love your feedback.

0 comments: