DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 963,673 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Masihur Rahman Maruf
Masihur Rahman Maruf

Posted on

Locator Strategy: CSS Selector

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)

Join the One Year Club

You can earn this badge by being a registered member of the DEV Community for at least one year. Create an account and get started today.