CSS selector contains text in Selenium is valid?

CSS Selector

Hello guys in this blog we are going to learn about CSS selector contains text() function before going to the point I would like to tell that most of the clients prefer CSS selector Over the xpath there is that the xpath is very fragile it can break with the single change into the dome structure and it is not preferred because of its dependency on the other element at the top if you’re using absolute xpath.

CSS selector is preferred because it is very fast and easy to write at the beginning you may face difficulties with CSS selector but when you get used to it you will not face any difficulties. we can do all the operations in CSS selector as we do in xpath.

Let me tell you one thing that there is no any text() function in CSS as we have in xpath

So if you want to identify an element with its displayed text on the web page then we have to use xpath for it

<html>
<a id = 'abc'>Ask Question</a>
</html>

Xpath :

//a[text()="Ask Question"]

So in the above example you can see text function of expert has been used to identify ask a question text and if you want to do same in CSS selector you cannot use text function act as its not present for the CSS selector you will have to go with some other method.

CSS Selector :

so if you want to identify about element in CSS selector you have to use the ID attribute of element 

Like used in the below example

[#abc]

In the below table you can see some example I have given using CSS selector

Locator CSS selector equivalent
By class name "the-class"
.the-class
By ID "the-id"
#the-id
By tag name "h1"
h1
By name "the-name"
*[name='the-name']

If you want to know what are the different locators in Selenium you can go and check if different locators in Selenium

Author: Saad Mansuri

Leave a Reply

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