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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<html> <head> <title>Total-QA - Future of Software Testing</title> <head> <body bgcolor="Pink"> <ol> <h1>Selenium Components</h1> <li>RC</li> <li>IDE</li> <li>WebDriver</li> <li>Grid</li> </ol> </body> </html> |
Identify the Value IDE using the nth-of-type(index) as follows
Identify the Value IDE using the nth-child(index) as follows
Let us see now if the html Structure is changed a new Heading Tag h1 is Added.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<html> <head> <title>Total-QA - Future of Software Testing</title> <head> <body bgcolor="Pink"> <ol> <h1>Selenium</h1> <h1>Components</h1> <li>RC</li> <li>IDE</li> <li>WebDriver</li> <li>Grid</li> </ol> </body> </html> |
Identify the Value IDE using the nth-of-type(index) as follows
Identify the Value IDE using the nth-child(index) as follows
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/