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.
If your attributes that you need are prefixed with data you should be able to use the dataset for the element which will shrink your execute script by a bit:
You can expand javascript's
Element
type and addgetAttributes()
function:demo
then you can test integrity of attributes using the same method you use for one attribute:
You have to use
browser.executeScript()
function call instead of protractor API sinceElement.attributes
is out of protractor API implementation:Remember that when saying attributes, it means a named map structure instead an array in the context of DOM model. Which means you have to use the NamedNodeMap to access collection of Attr objects.
It works as the same way as that in @alecxe's answer without the iteration part.
Use
executeScript()
to execute a script that forms a list of attributes reading them fromelement.attributes
(js part inside is taken from here):Here
attrs
would contain a dictionary/object of element attributes with keys as attribute names and values as attribute values.Demo (using angularjs.org tutorial page, getting all attributes for a
header
):Not really beautiful and compact, but works for me. Would be happy to see better alternatives.
UPDATE (an improvement to the approach above):
It would also work if I would define a regular function and pass it in: