offthegrass
offthegrass

Reputation: 456

check if an element has any attribute from a given array

If I have an attribute disabled, and I want to check if an element has this attribute before running a function, I can use

if element.hasAttribute('disabled')

If I have several attributes that relate to the same function, such as

attributes = [disabled, something, another]

How can I use if element.hasAttribute('attribute') to check for any of the attributes in the array?

Update:

I actually only have two items in my array, so I did

if el.hasAttribute('noink') || el.hasAttribute('disabled')

The responses below are also viable and I would use them if I had a larger array.

Upvotes: 0

Views: 844

Answers (4)

offthegrass
offthegrass

Reputation: 456

Update:

I actually only have two items in my array, so I did

if el.hasAttribute('noink') || el.hasAttribute('disabled')

The responses below are also viable and I would use them if I had a larger array.

Upvotes: 0

Radio
Radio

Reputation: 2853

A bit more compact...

function hasAttributes(e, l){
    var t = [];
    for(var i in l){
        t.push(e.attributes[l[i]] !== undefined);
    }
    return t;
}

use:

var myList = ["disabled", "something", "another"];
var myElement = document.getElementById("test");
console.log(hasAttributes(myElement, myList));

Or just true false for all or nothing case:

function getAttributes(e, l){
    var t = [];
    for(var i in l){
        if(e.attributes[l[i]] === undefined){
            return false;
        }
    }
    return true;
}

Upvotes: 0

adeneo
adeneo

Reputation: 318182

How about a function

function hasAttributes(element, arr) {
    return [].slice.call(element.attributes).some(function(attr) {
        return arr.indexOf(attr.name) !== -1;
    });
}

to be used as

var attributes = ['disabled', 'something', 'another'];
var element    = document.getElementById('some_id');

var has_attr   = hasAttributes(element, attributes);

FIDDLE

Upvotes: 2

Mukund Kumar
Mukund Kumar

Reputation: 23201

apply for loop:

  var isAttr=false;
    for(key in attributes){
        if(element.hasAttribute('attribute')){
        console.log('the attribute'+attributes[key]+ 'is attach to element');
        isAttr=true;
       }
    }
 console.log('element has any of array element as attribute:'+isAttr)

Upvotes: 0

Related Questions