Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS selector based on parent and child nodes?

Is there a way I can express the following as a single CSS selector? (Or will I have to find some other way to do this besides using a CSS selector until Level 4 is a reality? See: http://www.w3.org/TR/selectors4/#subject)

I want …

  • the only div (of unknown class)
  • that has a div grandchild titled "foo"
  • and that has a grandparent div with class "bar baz"

There are two divs on the page that have a grandchild titled "foo". I want to match only the one that also has a grandparent div with the class "bar baz".

This is for use with Selenium Webdriver.

like image 833
user1011471 Avatar asked Dec 06 '25 06:12

user1011471


1 Answers

Unfortunately, this isn't possible with a single CSS selector.

The criterion "has a grandparent div" requires the subject selector introduced in Selectors level 4, which would result in the following selector (assuming "titled" means "has a title attribute equal to"):

div.bar.baz > * > !div > * > div[title="foo"]

And there isn't a way to select the nth or only occurrence of an element in an entire page, so your first criterion can never be satisfied using a CSS selector. Not to mention the above won't work anyway since currently there isn't any browser that implements Selectors 4.

You're probably better off using DOM traversal or XPath instead. The XPath expression I'm thinking of is much more complicated, but it can find the only occurrence of an element in an entire page (if I have it correct that is... you may have to test it on your own page):

(
  //div[contains(concat(' ', @class, ' '), ' bar ') and contains(concat(' ', @class, ' '), ' baz ')]
    /*
      /div[child::*/child::div[@title="foo"]]
)[1][last()]

If you're looking for an exact match on the class attribute for the grandparent, use this XPath instead (again untested):

(
  //div[@class="bar baz"]
    /*
      /div[child::*/child::div[@title="foo"]]
)[1][last()]
like image 79
BoltClock Avatar answered Dec 09 '25 21:12

BoltClock



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!