Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS Selector-How to locate Parent Element

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.

like image 640
J_Coder Avatar asked Jun 23 '15 04:06

J_Coder


People also ask

How do I navigate to a 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.

How do I get parent element in querySelector?

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.

Can CSS be used to find child => parent page element?

Yes, it's possible. We can check with CSS @supports rule like the following.

How do I traverse from parent to child in CSS selector?

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 > *.


2 Answers

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(".."));
like image 98
alecxe Avatar answered Oct 07 '22 07:10

alecxe


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

like image 23
Irina Livkovich Avatar answered Oct 07 '22 08:10

Irina Livkovich