webdriver findElement inside findElements

i am wondering if there is an efficient way to find element inside list of elements example :

WebElement menuItem;
List<WebElement> allMenuItems = driver.findElements(By.className("x-menu-list-item"));      
    for(WebElement item : allMenuItems){
        if(item.getText().equals("aaa"){
                      menuItem = item;
                      break;
                    }
    }
menuItem.click();

so instead of looping through to find element based on text, is there an efficient way to find element from the list of elements?

Answers


Yes. You can build your initial query to find your element immediatelly.

If you don't need to search by text, you can mostly use CSS selectors for maximum readability and efficiency.

If, however, you need to search by text, you must use an XPath expression.

For example, your code could be simply

WebElement menuItem = driver.findElement(By.xpath("//*[contains(@class, 'x-list-menu-item') and contains(text(), 'aaaa')]"));

Note that the class finding with XPath is not exactly correct. Search for it online to find the right construct.


Need Your Help

Newline character into textfile using QFile

qt qt4

i want to put a newline into a txt file, i tried with many alternative with so many help from this forum but i am getting always unknown character always. Please help

In proper HTML, must an <input> be in a <form>?

html forms input standards specifications

I need a few input elements, but their values won't be submitted anywhere - they're just going to be manipulated by some client-side JavaScript. Do I have to place them in a &lt;form&gt; to have le...