Let’s be honest, CSS sometimes can get a little tricky and confusing to understand. Especially with the onset of CSS3 and all these new CSS3 selectors and pseudo classes, it’s quite possible that many of us might still be trying to catch up with the new selectors. Well, only-of-type is one such new CSS3 pseudo class that can be a little confusing. So let’s dive deep into understanding the only-of-type CSS pseudo class selector.

What is only-of-type CSS selector / Pseudo Class selector?

In simple terms, the purpose of only-of-type pseudo class is to select or filter out that element which is the only one (single one or lonely one) of a ‘certain type’ (<a> , <p> etc) under its parent element. Which means that if there is an anchor, which is the ONLY anchor within its parent element, then you can target it using the only-of-type pseudo class by using a:only-of-type{} . If there are other anchors within the same parent, then none of the anchors would be selected as they would not be the “only one” within their parent element and has siblings of the same type (<a>). However, if there is only one anchor and the other elements are say a paragraph tag, even then the only-of-type selector is applicable on it.

Let’s understand this better with the help of the following code and illustration.

This is how the code would render on a browser :

only-of-type example

The above DOM can be also presented as a tree structure for representation purposes. Let’s take a look at it.

only-of-type explained

As you can notice, right under the Body there are two elements a Div with class “main-wrapper” and an Anchor. Please note that this anchor is the ONLY anchor directly under the Body tag. Similarly under the main-wrapper Div there is a span tag which has an Anchor and a Paragraph under it. Here too you can notice that the Anchor is the ONLY anchor under the span and the other sibling is a paragraph. Same goes with the Anchor which is the ONLY anchor within the first list item. The second list item has two anchors within it and hence do not qualify as only-of-type element.

The purpose of only-of-type selector is to target the elements which are the only one of that type within its parent. These elements don’t have a sibling of the same type but can contain siblings of any other type. This selector is a very useful one and can easily avoid usage of JavaScript to target such elements for the purpose of styling or hiding. We’ll go ahead and play around with the only-of-type selector and let us know your experiences with it.