Get all element attributes using protractor

alecxe picture alecxe · Dec 29, 2014 · Viewed 11.5k times · Source

According to the documentation, to get a single attribute by name you can use .getAttribute() on a WebElement:

var myElement = element(by.id('myId'));
expect(myElement.getAttribute('myAttr')).toEqual('myValue');

But how can I get all of the attributes that an element has?

There is no information about this use case/functionality in the Protractor API.

Answer

neo picture neo · Jan 7, 2015

You can expand javascript's Element type and add getAttributes() function:

Element.prototype.getAttributes = function() {
    return (function (node) {
        var attrs = {};
        for (var i=0;i<node.length;i++) {
            attrs[node.item(i).name] = node.item(i).value;
        }
        return attrs;
    })(this.attributes);
};

demo

then you can test integrity of attributes using the same method you use for one attribute:

var myElement = element(by.id('myId'));
expect(myElement.getAttributes()).toEqual({'attr1': 'value1', 'attr1': 'value1', ... });