smeeb smeeb - 7 months ago 19
HTML Question

Using CSS selectors to get first child from a nested element

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="" 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
child of a class named
, 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?


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

More information: