In my previous blog I discussed about XPath. In this blog I will try to focus on some most important concepts in CSS Selector. I will strongly recommend to read the Locator Strategy: XPath before reading this blog.
CSS Selector should be preferred when we don’t have any suitable Id or name. Selectors are patterns that match against elements in a tree, and as such form one of several technologies that can be used to select nodes in an XML document. For more information visit W3C Recommendations.
In CSS, “>” is used to define the direct child relationship between the elements. For example:
Body tag is the direct child of html tag.
If an element is the any child or grand child of the current element, but not a direct child in CSS it is defined by whitespace.
That means, img tag is a descendant of div tag, but not a direct child.
For Id attribute in an element CSS has a special symbol “#”. Unlike XPath you can find element directly using Id.
This will find the element that has id ‘products’.
Like Id you can identify element using class name. For that you need to use “.”.
You can use above selector to find element that has class name setter.
CSS support finding elements using attribute other then Id and class. Have a look on the following example:
Finding an image element using attribute title.
You can find element using multiple attributes.
CSS supports use of wildcard characters like “^”, “$” and “*”.
You can use “^” with attribute name to simulate ‘starts-with’. Let’s see an example:
This will find any image tag that has an attribute named ‘title’ with value starts with ‘En’.
Let’s see the use of “$”.
It simulates ‘ends-with’. Will find an image tag that ends with value ‘sh’.
“*” is used to find any specific pattern in the value of attributes.
Here it will search for image tag with a pattern ‘n_U’.
In this blog, I focused on the basic usage of CSS Selectors. Next time I will explain some of the advanced topics of CSS Selectors. Till then practice…