Say I have the following
<div class="facetContainerDiv">
<div>
<label class="facetLabel">
<input class="facetCheck" type="checkbox" />
</label>
<label class="facetLabel">
<input class="facetCheck" type="checkbox" />
</label>
<label class="facetLabel">
<input class="facetCheck" type="checkbox" />
</label>
<label class="facetLabel">
<input class="facetCheck" type="checkbox" />
</label>
<label class="facetLabel">
<input class="facetCheck" type="checkbox" />
</label>
</div>
</div>
Now I want to put a check mark on the checkbox based on the index I provide. So I write a method like below
How do I access all elements inside the div class="facetContainerDiv" ?
I tried
List<WebElements> elementsList = driver.findElements(By.cssSelector(".facetContainerDiv"));
for(WebElement checkBox:elementsList) {
int i=0;
checkBox = elementsList.get(i);
bla bla bla..
}
in the above code elementsList has only one element with "type" as null.
This question is related to
java
selenium
selenium-webdriver
You're asking for all the elements of class facetContainerDiv
, of which there is only one (your outer-most div). Why not do
List<WebElement> checks = driver.findElements(By.class("facetCheck"));
// click the 3rd checkbox
checks.get(2).click();
alternatively, you can try writing a specific element:
//label[1] is the first element.
el = await driver.findElement(By.xpath("//div[@class=\"facetContainerDiv\"]/div/label[1]/input")));
await el.click();
More information can be found here: https://www.browserstack.com/guide/locators-in-selenium
I'm not sure if your findElements statement gets you all the divs. I would try the following:
List<WebElement> elementsRoot = driver.findElements(By.xpath("//div[@class=\"facetContainerDiv\"]/div));
for(int i = 0; i < elementsRoot.size(); ++i) {
WebElement checkbox = elementsRoot.get(i).findElement(By.xpath("./label/input"));
checkbox.click();
blah blah blah
}
The idea here is that you get the root element then use another a 'sub' xpath or any selector you like to find the node element. Of course the xpath or selector may need to be adjusted to properly find the element you want.
Source: Stackoverflow.com