Akash Chavan
Akash Chavan

Reputation: 335

How to locate element in Selenium with attribute only, irrespective of the what value attribute holds

How to locate an element in Selenium with attribute only?

An element in DOM is as below:

<div data-test="test" data-app-test="xyz">

I can form the XPath as below:

//div[@data-app-test="xyz"]

but the problem is that @data-app-test can have dynamic value, so I want to locate an element which contains attribute "data-app-test", but its value can be anything. How can I do that?

Upvotes: 0

Views: 2435

Answers (5)

Ratmir Asanov
Ratmir Asanov

Reputation: 6459

You can do it with CSS Selector:

div[data-app-test]

Upvotes: 1

Ishita Shah
Ishita Shah

Reputation: 4035

You can simply retrieve using:

driver.findElement(By.xpath("//div[@data-test='test']")).getAttribute("data-app-test");

Upvotes: 0

Artem Karp
Artem Karp

Reputation: 19

You can do quite not good in term of performance but let's say for some cases reliable way:

1) Find a root element(container) that contains all <div>s;

2) driver.findElement(containerLocator) .findElements(locatorDiv) .forEach(element -> "yourAttribute".equals(element.getAttribute(attribute))).

So main idea to use element.getAttribute(NAME).

Another way just use XPath for selection.

For example, //node[not(@*)] this should return all elements without attributes.

Upvotes: 0

Artem Karp
Artem Karp

Reputation: 19

@* is short for attribute::* and selects all attributes of the context node:

  //div[@*]

Upvotes: 0

choroba
choroba

Reputation: 241808

Just specify the attribute exists, don't compare its value to anything:

//div[@data-app-test]

Upvotes: 4

Related Questions