Home > Back-end >  Choose the correct element from the list of objects with the same className
Choose the correct element from the list of objects with the same className

Time:09-17

Quick one, i am trying to avoid using xpath and using css selectors due to performance issues xpath can have so i would like to know the right approach of locating for example "A" in the list

<div class="input-search-suggests" xpath="1">
<div class="input-search-suggests-item">A</div>
<div class="input-search-suggests-item">B</div>
<div class="input-search-suggests-item">C</div>
</div>

Currently i am locating A using xpath / span but it would be indeed sufficient locating all elements and then grabbing A from the list that have same class which is "input-search-suggests-item"

@FindBy(xpath = "//span[contains(text(),'A')]")

CodePudding user response:

CSS_SELECTOR does not have support for direct text what xpath has.

What this means is, for the below xpath

xpath = "//span[contains(text(),'A')]"

based on text A you can not write a css selector.

Instead to locate A using css selector, you can do :

div.input-search-suggests > div.input-search-suggests-item

In Selenium something like this :

@FindBy(cssSelector= "div.input-search-suggests > div.input-search-suggests-item")

Even though it will have 3 matching nodes, but findElement will take the first web element.

Also you may wanna look at nth-child(n)

div.input-search-suggests > nth-child(1)

to make use of index to locate A, B, C

Here is the Reference Link

  • Related