0

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.

4 Answers 4

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

thanks, I may use something like this as an attribute alternative to classie in the future.
why you use [].slice.call why not Array.slice.call ? is there any difference between these two @adeneo
Yes, there's a difference, [].slice.call is a shortcut for Array.prototype.slice.call
0

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)

1 Comment

interesting, I wouldn't have though of this. I don't have enough attributes to warrant it, though. thanks for the response.
0

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;
}

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.