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:
<button type="submit" class="okButton">
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:
WebElement element = driver.FindElement(By.CssSelector(".okButton"));
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 the code we need would be:
String script = "return window.getComputedStyle(document.querySelector('.okButton'),':after').getPropertyValue('content')";
String content = (String) js.ExecuteScript(script);
Assert.assertEqual("Content displayed after the button.", content);