Preface:
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.
Syntax:
Direct Child:
In CSS, “>” is used to define the direct child relationship between the elements. For example:
html>body
Body tag is the direct child of html tag.
Descendent(sub-child):
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.
div img
That means, img tag is a descendant of div tag, but not a direct child.
Finding Element using Id and Class attributes:
For Id attribute in an element CSS has a special symbol “#”. Unlike XPath you can find element directly using Id.
#products
This will find the element that has id ‘products’.
Like Id you can identify element using class name. For that you need to use “.”.
.setter
You can use above selector to find element that has class name setter.
Finding elements using other attributes:
CSS support finding elements using attribute other then Id and class. Have a look on the following example:
img[title='English']
Finding an image element using attribute title.
Finding elements using multiple attributes:
You can find element using multiple attributes.
img[title='English'][alt='United States']
Use of Wildcards:
CSS supports use of wildcard characters like “^”, “$” and “*”.
You can use “^” with attribute name to simulate ‘starts-with’. Let’s see an example:
img[title^='En']
This will find any image tag that has an attribute named ‘title’ with value starts with ‘En’.
Let’s see the use of “$”.
img[title$='sh']
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.
img[id*='n_U']
Here it will search for image tag with a pattern ‘n_U’.
Conclusion:
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…
Top comments (0)