How to get HTML5 data attribute using xpath?

How do I get the first table (table1) using xpath for Webdriver?

<span> <table> ... </table>
</span>
<span> <table> ... </table>
</span>

I am able to get all data-id elements but I want to filter within it for text table1 to get the exact element.

This did not work!

driver.findElement(By.xpath("//@*[starts-with(name(),'data-id') [contains(text(),'table1')]]")); 

4 Answers

You get the table like this:

//span[@data-id='table1']/table

Select the data-id attribute and get the child element of name table.

Answering my own question...This appears to get the exact element.

driver.findElement(By.xpath("//*[@data-id='table1']"))
1

I think you can also use the cssSelector

driver.findElement(By.cssSelector("[data-id='table1']"));

Try (built this be combining xpath: find a node that has a given attribute whose value contains a string and Getting attribute using XPath)

driver.findElement(By.xpath("//*[contains(@data-id, 'table1')]/@data-id"));

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like