4

I am trying to understand CSS selectors better and am fiddling around with Google/Gmail. When you go to Google's home page and enter "gmail", it will automatically present you with search results for that term. I want to write a CSS selector that will find the first one (that is, the link to Gmail, since it should always be the first result). The HTML for these results looks like:

<div class="srg">
  <div class="g">
    <h3 class="r">
      <a href="https://mail.google.com/" onmousedown="return rwt(a bunch of stuff I omitted for brevity)">Gmail - Google</a>

      ...

Based on what I could gather from the W3schools CSS docs, it seems like I want the first <a> child of a class named r, or:

h3.r a:first-child

However, the tool I'm using doesn't recognize this as the first link. So I ask: is this a correct selector for the Gmail (first) link, or did I go awry somewhere?

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
smeeb
  • 27,777
  • 57
  • 250
  • 447
  • 2
    What browser and "tool" are you using? – JohannesB May 24 '16 at 16:55
  • Geb, browser automation. I intentionally didn't put that in the question because I wanted to first rule out a bad CSS selector (vs. a misuse or bug in Geb). For some reason Geb liked the accepted answer. – smeeb May 24 '16 at 17:45
  • 1
    @smeeb: Unfortunately, selector implementations don't do a terribly consistent job at following the spec (and this is true not only of browser automation tools but even of browsers themselves), so you'll find that you'll have to specify the tool you're using pretty much all the time. – BoltClock May 25 '16 at 06:03

3 Answers3

3

Well, the anchor element you're referring to is the only child of the h3.r parent.

So :first-child, :last-child and :only-child would all apply.

enter image description here

A simple h3.r > a (child selector) or h3.r a (descendant selector) should suffice, assuming it's unique in the document.

Your selector – h3.r a:first-child – should, technically speaking, work as well.

Based on the image above, an attribute selector may also work:

h3.r a[data-href="https://mail.google.com/"]

More information: https://www.w3.org/TR/css3-selectors/#selectors

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
0

Within Geb, you can also use

`$("h3.r").find("a")[0]

to select the first child.

0

Using :first-of-type is very similar to :nth-child, but there is a critical difference: it is less specific.

In the example above, if we had used p:nth-child(1), nothing would happen because the paragraph is not the first child of its parent (the <article>). This reveals the power of :first-of-type: it targets a particular type of element in a particular arrangement with relation to similar siblings, not all siblings.

Reference: https://css-tricks.com/almanac/selectors/f/first-of-type/

sɐunıɔןɐqɐp
  • 3,332
  • 15
  • 36
  • 40