9

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.

1
  • css does not give you the flexibility of walking down the nodes as xpath does Commented Jun 23, 2015 at 4:29

4 Answers 4

20

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(".."));
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

If the parent is say div, you could try something like below

div div[id='gf-BIG']

Comments

0

There is no direct way(like using :parent OR :preceding), we can use CSS Selector for finding the parent element.

  1. CSS Provides support for siblings
  2. CSS Provides support for childs
  3. CSS Provides support for element which has specific child element with :has() function. This may help at some extent for finding parent. (Reference: Is there a CSS parent selector?)

However, we can not find Parent element directly using CSS.

Needless to say - CSS selector is best way to find elements as far as performance matters.

1 Comment

have a look at this post stackoverflow.com/questions/1014861/… hope that helps

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.