Taiko: How to get attribute value

Created on 14 May 2019  路  4Comments  路  Source: getgauge/taiko

Is there some way to get attribute values from a element on the page?

Expected behavior

In code I want to get the href attribute from a link tag.
let href = await $("//a[contains(@class,'HotTipLink')]/@href").text();
would expect href to be an array of links ['tip1.html', 'tip2.html', 'tip3.html']

Actual behavior

I get an empty array.
I understand that text() is not the same as attribute value, but cannot find anything in the API that would give me either access to the DOM element or attribute values.

Steps to reproduce

await goto('http://www.example.com')
let href = await $("//a/@href").text();
console.log(href);

Output is [] was hoping for http://www.iana.org/domains/example

Versions

node= 10.10.0
taiko = 0.6.0

Most helpful comment

There is no direct api to get attr and value as of now. evaluate api can be used as of now,
eg: evaluate($('a'), (elem) => {return elem.getAttribute('href')})

All 4 comments

There is no direct api to get attr and value as of now. evaluate api can be used as of now,
eg: evaluate($('a'), (elem) => {return elem.getAttribute('href')})

Note: If $ would select an array of elements, the code above would return the href of the first element.

eg:

<a href="one">1</a>
<a href="two">2</a>
<a href="three">3</a>

js:

const results = await evaluate($('a'), (elem) => {return elem.getAttribute('href')})

console.log(results);

output:


@davidonlaptop The $ returns an ElementList which by default delegate the actions to first element.
To access all the elements you need to use $('a').elements(), it will give you all the elements. Then you can loop over the elements and run evaluate to get the href attribute.

For example:

let elements = await $('a').elements();
let attributePromises = elements.map(e => {
   return evaluate(e, elem => {return elem.getAttribute('href');});
});
console.log(await Promise.all(attributePromises));

Amazing!

Thanks for the fast response!

Was this page helpful?
0 / 5 - 0 ratings