Search code examples
javascriptapiprotractorend-to-end

Get all element attributes using protractor


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.


Solution

  • 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', ... });