One thing that I love about CSS3 is is the new addition of selectors that allow us to target elements specifically without relying on the class, id or other element attribute, and one that we will cover here is the following selector, :first-of-type.

The :first-of-type selector will target the first child of the specified element, for example, the snippet below will target the first h2 on the web page.

h2:first-of-type {
/* style declaration */
}

The :first-of-type is also equal to :nth-of-type(1), so rather than selecting only the first of the type, we can further select the second, the third and so on. The following snippet will target the second h2 element on the web page.

h2:nth-of-type(2) {
/* style declaration */
}

:first-of-type” vs. “:first-child”

It may seem like these two selectors are doing the same thing, but that’s not the case. Let’s see the following demonstration:

Let’s say we have five paragraph elements wrapped within a div, like this:

The “Last” Selector

Where there is the “first”, then there will also be the “last”.

The reverse of the two selectors we have discussed above are the following two selectors; the :last-child and the :last-of-type. They basically are the same as the above two, except they do target the last child of the specified element.

For example, this snippet below will target the last paragraph inside the div.

So, if all these selectors we’ve mentioned here are really required for your webite, you can use a JavaScript Library called Selectivizr to emulate those CSS3 selector’s functionality.

The Selectivizr is dependent on other JavaScript Libraries in order to work, such as the jQuery, Dojo, Prototype and MooTools; and seeing from the comparison table in the official website, MooTools seems to be able to handle all the selectors.