What is the Pseudo-element
There are times, while writing automated tests on the web UI, you will come across some elements like this:
These are called pseudo elements, and they are the CSS keywords added to the element’s selector, allowing you to style specific parts of that element. It can be used to:
- Style for the first letter, or the first line of an element.
- Inserts content before or after the content of the element.
Other pseudo-elements you may encounter are:
- before, works the same way as after, except it applies to text added before the element
- first-line, which applies the style to the first line in the element (usually paragraph elements).
- placeholder, which means the text is placed in the input or textarea element
- selection, applied to the text currently highlighted by the user
So how to work with the pseudo elements in selenium?
Now comes the hard part. If we need to interact with a pseudo element, Selenium WebDriver doesn’t give us the option to do so.
Let’s say we have an element with this HTML:
1 2 3 4 | <button type="submit" class="okButton"> "Submit" </button> |
And CSS
1 2 3 4 | .okButton:after { content: 'Content displayed after the button.'; } |
And our testing request is to verify the content displayed in the :: after block. Since this is not an ordinary element, we cannot define it using regular Selenium locators.
For example if we write like this:
1 2 3 | WebElement element = driver.FindElement(By.CssSelector(".okButton")); System.out.prirntln(element.Text); |
Selenium will not return us any text inside the pseudo element css
Try with other pseudo elements like “.okButton :: after” or “.okButton: after you will still get the NoSuchElementException .. error message.
So what is the solution? It’s Javascript because javascript is a front-ent programming language it allows us to delve deeper into HTML and CSS code and allows us to get content from dummy elements in Selenium.
So the code we need would be:
1 2 3 4 5 | String script = "return window.getComputedStyle(document.querySelector('.okButton'),':after').getPropertyValue('content')"; IJavaScriptExecutor js = (IJavaScriptExecutor)_driver; String content = (String) js.ExecuteScript(script); Assert.assertEqual("Content displayed after the button.", content); |
The JavaScript executor will run a script that gets the content inside :: after the dummy element. We can then store this content in a string variable and compare it with another expected value
Conclude:
Although Selenium itself does not allow interaction with dummy elements, we can use the JavaScript runtime in our code and get the values we need to include in our tests.
Reference Link: https://blog.testproject.io/2021/04/06/working-with-pseudo-elements-in-selenium/