Reputation: 383
I would like to find all elements within a root div element.
This is what I am doing:
@Keyword
public boolean verifySlotsOrder(int numOfSlots){
WebDriver driver = DriverFactory.getWebDriver()
WebElement slotsGrid = driver.findElement(By.id('js-' + numOfSlots + '-grid'))
List<WebElement> children = slotsGrid.findElements(By.xpath('//*[@id="js-' + numOfSlots + '-slot"]'))
for(int i = 0; i < children.size; i++){
KeywordUtil.logInfo(children[i].getText())
}
//return true or false once the slots order is validated
}
The problem with this code is that the method is not working how I assumed it would work. I the xpath would match a portion of each child WebElement's xpath and hence it would be added to my list. My id sequence for elements within the root div is:
js-numOfSlots-slot<slotNum>
where 1 <= slotNum <= numOfSlots
How can I properly generate a list of WebElements that follow this sequence of IDs and have a common parent WebElement. Also is this possible with Katalon TestObjects?
Here is the HTML. Note that I only want the immediate children, not all the decendents.
Update:
I am able to get all decedents of my root div by doing this:
List<WebElement> children = slotsGrid.findElements(By.xpath("//*[contains(@id, 'js-8-slot')]"))
and if I add /div/div/div
at the end of my xpath, I get certain child elements, but I am still not sure how to properly get only the first layer child elements (immediat children).
Upvotes: 2
Views: 3264
Reputation: 383
An easier way of doing this is by using ("*")
which gives all the direct child elements of the context node.
Implementation:
WebDriver driver = DriverFactory.getWebDriver()
//get the parent element
WebElement slotsGrid = driver.findElement(By.id('js-' + numOfSlots + '-grid'))
//use the parent element to get all the immediate children
List<WebElement> children = slotsGrid.findElements(By.xpath("*"))
Upvotes: 2
Reputation: 14145
Here is the xpath to get all the slot divs.
CSS:
div[id^='js-8-grid'] >div[id^='js-8-slot']
xpath:
//div[contains(@id,'js-8-slot') and parent::div[@id='js-8-grid']]
Implementation:
@Keyword
public boolean verifySlotsOrder(int numOfSlots){
WebDriver driver = DriverFactory.getWebDriver()
# don't need the grid here, we can access the slots directly
List<WebElement> children = slotsGrid.findElements(By.xpath("//div[contains(@id,'js-" +Integer.toString(numOfSlots) +"-slot') and parent::div[@id='js-" +Integer.toString(numOfSlots) +"-grid']]"))
for(int i = 0; i < children.size; i++){
KeywordUtil.logInfo(children[i].getText())
}
}
Upvotes: 2