I've tried
private WebElement getParent(final WebElement webElement) {
return webElement.findElement(By.xpath(".."));
}
But I'm getting:
org.openqa.selenium.InvalidSelectorException: The given selector .. is either invalid or does not result in a WebElement. The following error occurred: InvalidSelectorError: The result of the xpath expression ".." is: [object XrayWrapper [object HTMLDocument]]. It should be an element. Command duration or timeout: 10 milliseconds For documentation on this error,
Is there a way to get the parent of current element? Thanks
Also we can identify the parent element of a known element with the help of Javascript Executor. We have to pass the Javascript command return arguments[0]. parentNode and the webelement as parameters to the method executeScript. The parentNode command in Javascript is used to point to the parent of an element.
getText() Method in SeleniumThis method helps retrieve the text, which is basically the innertext of a WebElement. getText() method returns string as a result. It removes the whitespaces if present in the front and back of the string.
We will then find the XPath of the parent element node of the current node using parent syntax, as shown below screenshot. XPath of Parent node: //input[@id = 'text']//parent::span. It will then select the parent node of the input tag having Id = 'text'. XPath(Parent node): //input[@id = 'text']//parent::*.
getText() is a method which gets us the visible (i.e. not hidden by CSS) innerText of this element, including sub-elements, without any leading or trailing white space. The getAttribute() method is declared in the WebElement interface, and it returns the value of the web element's attribute as a string.
There are a couple of ways you can accomplish this. If you insist on using XPath to do it, you need to add the context node to the locator, like this:
WebElement parentElement = childElement.findElement(By.xpath("./.."));
Alternatively, you can use the JavascriptExecutor
interface, which might be slightly more performant. That would look like this:
// NOTE: broken into separate statements for clarity. Could be done as one statement.
JavascriptExecutor executor = (JavascriptExecutor)driver;
WebElement parentElement = (WebElement)executor.executeScript("return arguments[0].parentNode;", childElement);
Alternatively, can you try using Javascript Executor?
WebElement childElement = driver.findElement(By.id("someIdHere"));
WebElement parent = (childElement) ((JavascriptExecutor) driver)
.executeScript("return arguments[0].parentNode;", childElement);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With