Checking the elements after the CSS selector in Protractor for content verification

My HTML document contains the following element:

HTML:

<hmtl>
    <head>
        <style>
            label::after {
            content: " *"
            }
        </style>
    </head>
    <body>
        <label> I'm mandatory</label>
    </body>
</hmtl>

When rendered in a web browser, it displays as:

I'm mandatory *

Query Selector

>getComputedStyle(document.querySelector('label')).content
<"normal"

However, instead of seeing "*", I get the result "normal". This confuses me as to where this is coming from. Is my approach correct for testing the content of the ::after CSS selector?

I'm attempting to verify if there is a "*" after the label, yet unable to extract the value of the "content" property accurately. Once I am able to locate it using the browser DOM API, I intend to test this functionality in Protractor.

Update

After finding guidance on - Selenium WebDriver get text from CSS property "content" on a ::before pseudo element, I still question how to conduct this test using Protractor.

Answer №1

Understanding Window.getComputedStyle()

The Window.getComputedStyle() function allows you to retrieve an object that contains the computed values for all CSS properties of a specific element. It takes into account active stylesheets and resolves any basic computations within those values. You can access individual CSS property values using APIs provided by the returned object or by indexing with the CSS property names.

  • Syntax:

    var style = window.getComputedStyle(element [, pseudoElt]);
    
    element
        Specifies the Element for which you want to retrieve the computed style.
    pseudoElt (Optional)
        A string that specifies the pseudo-element to match. If omitted or set to null, it applies to real elements.
    
    The style returned is a live CSSStyleDeclaration object, meaning it automatically updates when the element's styles change.
    
  • You may also find relevant information in this discussion on selecting elements with pseudo-elements in WebDriver


Working with Pseudo-Elements

The getComputedStyle() method can extract style information from pseudo-elements like ::after, ::before, ::marker, and ::line-marker.

For example, consider this HTML snippet inside a <style> tag:

<style>
    label::after {
    content: " *"
    }
</style>

When implemented as follows:

<label> I'm mandatory</label>

To retrieve this generated content, you would execute the following script:

var label = document.querySelector('label'); 
var result = getComputedStyle(label, ':after').content;

console.log('the generated content is: ', result); // outputs ' *'

Additional Resources

Answer №2

const name = document.querySelector('name'); // "John";

console.log(name);


const nameAfter = getComputedStyle(name, ':after').content;

console.log(nameAfter == "John");
name::before {
  content: " *"
}
<name> I go by John</name>

Answer №3

My inquiry pertains specifically to protractor, so I am sharing the solution that resolved my issue. The initial confusion arose when I was receiving "normal" instead of " *".

>getComputedStyle(document.querySelector('label')).content
<"normal"

It turns out that ::after generates a pseudo child element within the label element.

Upon inspecting the <label> element in Chrome, I discovered the following HTML structure:

<label>
    I'm mandatory
    ::after
</label>

When I selected the <label> element and checked the Computed tab, the value for the content property appeared as normal.

However, upon clicking on the ::after pseudo-element, the Computed tab displayed the content property with a value of " *".

As pointed out in other responses, utilizing getComputedStyle() with the pseudo element as the second parameter is crucial for retrieving CSS property values for "::after". The challenge lies in the fact that protractor does not support an equivalent function like getComputedStyle(), thereby requiring us to resort to browser.executeScript() as illustrated below:

let labelHeader = 'I'm mandatory *';
// When implementing this in a real test scenario, the label element would be extracted from its parent
// container and passed as a parameter to browser.executeScript().

let label = element(by.css('label'));
browser.executeScript("return window.getComputedStyle(arguments[0], ':after').content",
                       label)
    .then ((suffixData: string) => {
     // The returned suffixData is '" *"', enclosed in double quotes.
     // Removing the first and last double quote characters

         suffixData = suffixData.slice(1, suffixData.length - 1);
         labelText += suffixData;
         expect(labelText).toBe(labelHeader);
     });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why do browsers, like Chrome, fail to update the .css file after making edits on a page? Is there a workaround for this issue?

Whenever I make changes to a .css file and upload it via ftp to my Apache web server, I always have to remember to clear the cache in my browser in order to see the correct page. What is the reason behind this issue? Shouldn't browsers automatical ...

"Step-by-step guide on positioning a video in the center over another

I am designing a landing page and I want to incorporate a background video with a centrally aligned logo on top of the video. My goal is for the center of the logo to always align with the center of the background image, regardless of how the page responds ...

What is the method for obtaining the CSS text content from an external stylesheet?

I've spent countless hours trying to achieve the desired results, but unfortunately, I haven't been successful. Below is a summary of my efforts so far. Any helpful tips or suggestions would be greatly appreciated. Thank you in advance. Upon rec ...

How to Align an Icon to the Right in a Bootstrap 4 Modal Title

I'm attempting to position two icons next to the close button within a Bootstrap 4 modal. Unfortunately, I am struggling to remove some unwanted margin-left that persists despite my best efforts. While inspecting the element, I was successful in achie ...

Which specific transitionend (or animationend) event should I use for this application?

I'm feeling a bit lost when it comes to using transitionend (or if I should be using animationend in this scenario). I'm not sure whether to utilize var, node, or box. Essentially, I am a complete beginner in this case. My goal is to have my div ...

Tips for recognizing and changing the frame source using Selenium

I have been utilizing Selenium and Python 2.7 with Firefox. I aspire for it to function in the following way, but I lack knowledge on how to code this. Driver.get('https://video-download.online') Url='https://www.youtube.com/watch?v=waQlR8 ...

table with stationary header

I have been attempting to keep the header fixed so that, when scrolling down to view other data, the <th> elements always remain visible. I tried following the instructions in this post, but when adding position: block to the styles for <th> an ...

What is the best way to increase padding in a Vuetify view element?

I have been attempting to increase the padding of my view by utilizing the "px-5" class on the container within the view. However, I am struggling to achieve the desired amount of padding. What I am aiming for is padding similar to what is shown in this sc ...

Mistake in Selenium: Incorrect element selection within for loop

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using OpenQA.Selenium; using OpenQA.Seleni ...

The issue with the left border color not functioning in JavaScript

Attempting to alter the border-left-color property using this script is resulting in a Uncaught SyntaxError: Unexpected token -. Is border-left-color actually supported? Javascript function logoChange() { var description = new Array (); description[0] ...

Learn how to troubleshoot and resolve a bug in the mobile Chrome browser that pertains to the position fixed feature

On the mobile version of Firefox, everything works perfectly. However, there seems to be a bug in Chrome with the fixed positioning. When scrolling, the header should change from absolute to fixed and the height should go from 65 to 35 pixels. Unfortunatel ...

A step-by-step guide on selecting multiple checkboxes with C# in Selenium

I am encountering an issue with checking both of these "checkboxes" while attempting to execute a Selenium test in C#. The code for the first checkbox works and successfully checks the box: driver.FindElement(By.XPath("//label[@for='LegitimateCompany ...

Header and footer not as clingy as advertised

I have created a basic bootstrap 4, flex page where the navigation and footer should be sticky, but for some reason they are not behaving as expected. I need help troubleshooting this issue: <!doctype html> <html lang="en"> <head> & ...

TimeoutError - Scraping Images from Google Using Selenium

I found some helpful code on this GitHub repository that I'm using to extract images from Google Image Search results. However, I'm encountering an issue within a certain try-exception block in my code: selenium.common.exceptions.TimeoutException ...

Is it feasible to achieve this layout using only CSS in Windows Internet Explorer 6?

<div class="article"> <span class="articleTitle"> Welcome to our blog!</span> <span class="articleIcon"></span> </div> I am looking to achieve the following: 1. The max-width of <div class="art ...

Change element position to relative while scrolling

I created a wrapper with an animation similar to the one on Apple's Airpods Pro page. It features a video that plays gradually as I scroll, with the text smoothly scrolling over it within a specific area (text-display). So far, this part is working w ...

I want to adjust the size of a <div> element as an image is being resized using Bootstrap's "img-responsive" class

When adjusting the browser size, the images are resized which is great because it's exactly what I intended. However, the lower part of the black area does not resize accordingly. This results in a black area appearing under the images when viewed on ...

Discover the best practices for integrating media queries using Radium within Material UI components

Having trouble applying a breakpoint to the Material UI component, Raised button. I have managed to make it work for regular divs, but not for the Material UI component. I attempted wrapping the button inside Radium import RaisedButton from 'materia ...

The verification of a button's presence in Robot framework fails after the button has been clicked

When using Robotframework, the 'Click Button' keyword is supposed to click the button as expected. However, sometimes there is an issue with checking if the button no longer exists or has been clicked. In these cases, additional checks such as &a ...

Is it possible to utilize CSS variables within a font lineup and ensure compatibility with older browsers?

Is it possible to utilize a CSS variable to store a font for cases where the user may not have the specified font installed? For example: :root { --common-font: Comic Sans MS; } .header1 { font-family: CoolFont1, var(--common-font); } Would o ...