Is there any way to locate parent element in CSS Selector? i am using below code but i am not getting the parent element.
WebElement we=dr.findElement(By.cssSelector("div[id='gf-BIG']:parent"));
I know there is a way in XPath but please let me know that how we can locate parent in CSS Selector.
The element>element selector is used to select elements with a specific parent. Note: Elements that are not directly a child of the specified parent, are not selected.
By using querySelector() and closest() methods is possible to get the parent element. querySelector() returns the first element that matches a specified CSS selector(s) in the document. closest() searches up the DOM tree for the closest element which matches a specified CSS selector.
Yes, it's possible. We can check with CSS @supports rule like the following.
In a css selector if we need to traverse from parent to child we use > symbol. To get all the immediate children we have to specify * symbol after parent node in the css expression. So the customized css should be parent > *.
Referring to the Is there a CSS parent selector? topic, there is no parent selector in CSS. Leave the "getting the parent" part to the XPath:
WebElement we = dr.findElement(By.cssSelector("div[id='gf-BIG']"));
WebElement parent = we.findElement(By.xpath(".."));
If it would help here is example how get it by xpath
WebElement parentElement = driver.findElement(By.xpath("//div[@id='gf-BIG']/parent::parentElementTag"));
parentElementTag - could be div/span/tr - depends on your case
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