基于父节点和子节点的CSS选择器? [英] CSS selector based on parent and child nodes?

查看:831
本文介绍了基于父节点和子节点的CSS选择器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法我可以表达以下作为一个单一的CSS选择器? (或者我将不得不找到一些其他的方式来做这除了使用CSS选择器,直到4级是现实吗?参见: http://www.w3.org/TR/selectors4/#subject

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)

我想...


  • only div(未知类别)


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

有两个div在页面上有一个孙子标题为foo。

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

这是与Selenium Webdriver配合使用的。

This is for use with Selenium Webdriver.

推荐答案

不幸的是,使用单个CSS选择器是不可能的。

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

有一个祖父类div需要在选择器级别4中引入主题选择器,这将导致以下选择器(假设标题意味着有 title 属性等于) :

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"]

没有办法选择第n个或只有在整个网页中出现元素,因此使用CSS选择器无法满足您的第一个条件。更何况上面的内容不会工作,因为目前没有任何实现Selectors 4的浏览器。

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.

你最好使用DOM遍历或XPath 。我想的XPath表达式要复杂得多,但它可以在整个页面中找到一个元素的唯一出现(如果我有正确的,你可能需要测试它在你自己的页面):

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()]

如果您要在祖父母的 class 属性上寻找完全匹配,请改用此XPath(再次未测试):

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()]

这篇关于基于父节点和子节点的CSS选择器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆