The Difference Between :nth-child and :nth-of-type CssSelector

The Difference Between :nth-child and :nth-of-type CssSelector



CssSelector is one of the most important Locator in Selenium WebDriver. Also Css is faster when compare to Xpath. In CssSelector to use index we use either nth-child(indexno) or nth-of-type(indexno).So, what is the difference between the two. Let us see an example in this tutorial.

Consider the following HTML Source as below:
In this example they are 4 li tags under the parent ol.

Identify the Value IDE using the nth-of-type(index) as follows

Usage of nth-of-type(indexno)

Usage of nth-of-type(indexno)


Identify the Value IDE using the nth-child(index) as follows
CssSelector tagName>nth-child(index)

CssSelector tagName>parent>child:nth-of-type(index)

Let us see now if the html Structure is changed a new Heading Tag h1 is Added.



Identify the Value IDE using the nth-of-type(index) as follows

nth-of-type(indexno)

nth-of-type(indexno)


Identify the Value IDE using the nth-child(index) as follows
Usage of nth-child(index)

Usage of nth-child(index)





Conclusion:
In Csselector nth-of-type(index) is more useful then nth-child(index). Even though the html
structure changes nth-of-type(index) will work.

Css Tricks for Reference: https://css-tricks.com/

Leave a Reply

Your email address will not be published. Required fields are marked *