Find element by attribute

JavaSeleniumSelenium Webdriver

Java Problem Overview


I am trying to find an element with Attribute. Well, I can find elements with Id, tagName, Xpath and all other predefined methods in Selenium. But, I am trying to write a method that specifically returns WebElement, given Attribute name and Value as input.

List<WebElement> elements = webDriver.findElements(By.tagName("Attribute Name"));
for(WebElement element : elements){
	if(element.getText().equals("Value of Particular Attribute")){
		return element;
	}
	else{
		return null;
	}
}

Assuming XPath is not an option, is there any other better ways to do this?

Java Solutions


Solution 1 - Java

You can easily get this task accomplished with CSS.

The formula is:

element[attribute='attribute-value']

So if you have,

<a href="mysite.com"></a>

You can find it using:

By.cssSelector("a[href='mysite.com']");

this works using any attribute possible.

This page here gives good information on how to formulate effective css selectors, and matching their attributes: http://ddavison.io/css/2014/02/18/effective-css-selectors.html

Solution 2 - Java

I do not understand your requirement:

> Assuming XPath is not an option ...

If this was just an incorrect assumption on your part, then XPath is the perfect option!

webDriver.findElements(By.xpath("//element[@attribute='value']"))

Of course you need to replace element, attribute, and value with your actual names. You can also find "any element" by using the wildcard:

webDriver.findElements(By.xpath("//*[@attribute='value']"))

Solution 3 - Java

Use CSS selectors instead:

List<WebElement> elements = webDriver.findElements(By.cssSelector("*[attributeName='value']"));

Edit: CSS selectors instead of XPath

Solution 4 - Java

As per the documentation:

By.id Locates elements by the ID attribute. This locator uses the CSS selector *[id='$ID'], not document.getElementById. Where id is the ID to search

so you can use the below code to search the DOM element with any given attribute as ID and value

By.id("element[attribute='attribute-value']"); 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKishore BanalaView Question on Stackoverflow
Solution 1 - JavaddavisonView Answer on Stackoverflow
Solution 2 - JavaSiKingView Answer on Stackoverflow
Solution 3 - JavaSizikView Answer on Stackoverflow
Solution 4 - JavaIrshadView Answer on Stackoverflow