简体   繁体   English

是否有CSS选择器可在整个页面中定位给定类型的第n个元素?

[英]Is there a CSS selector to locate nth element of a given type in the entire page?

I have Selenium-based tests that validate a page with several H2 sections. 我有基于Selenium的测试,可以验证包含多个H2部分的页面。 The sections used to belong to the same parent, so it was easy to assert for an expected text using CSS selectors (I use FluentAutomation API): 这些部分以前属于同一父级,因此使用CSS选择器(我使用FluentAutomation API)可以很容易地为期望的文本断言:

I.Expect.Text("Section Title").In("h2:nth-of-type(2)")

Now the page design has changed, so H2 sections are placed under different DIVs, so each of them is now 1st child if its parent. 现在页面设计已更改,因此H2部分放置在不同的DIV下,因此它们每个都成为其父级的第一个子级。 Now the selector h2:nth-of-type(1) selects all H2 sections, and h2:nth-of-type(2) selects none. 现在选择器h2:nth-​​of-type(1)选择所有H2部分,而h2:nth-​​of-type(2)不选择任何部分。

I would like not to be dependent on the structure of DIVs when selecting H2 sections. 选择H2部分时,我不想依赖于DIV的结构。 What I am trying to achieve is to select nth element of H2 type across the entire page. 我想要实现的是在整个页面中选择H2类型的第n个元素。 I know this is easy using jQuery, but is this possible using CSS syntax? 我知道使用jQuery很容易,但是使用CSS语法可能吗?

Simply change the target to point to your new <div> elements instead: 只需将目标更改为指向新的<div>元素即可:

div:nth-of-type(1) h2 { ... }
div:nth-of-type(2) h2 { ... }

This obviously depends on how many divider elements are on your page. 显然,这取决于页面上有多少个分隔符元素。 If you are using dividers not just to contain <h2> elements you could always give them a new class: 如果您使用分隔符不只是包含<h2>元素,您总是可以给它们一个新的类:

<div class="h2-container">
    <h2>Hello, world!</h2>
</div>
div.h2-container:nth-of-type(1) h2 { ... }
div.h2-container:nth-of-type(2) h2 { ... }

This does assume that all your divider elements are under the same parent, however. 但是,这确实假定所有除法器元素都在同一父对象下。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM