javascriptc#seleniumgetcomputedstylegetpropertyvalue

How to get child property value of a element property using selenium webdriver, NUnit and C#


I am testing websites using selenium webdriver and I am having difficulties getting the value of a property that is a child of another property. For me, this 2nd/child level is always coming back as null.

When trying to get a value of an upper level attribute/property it is working fine with the following code:

return Element1.GetAttribute("baseURI");
return Element2.GetAttribute("innerText");

Those above return the text/string that I am expecting. However if I try and get the value of a child property like the following:

return Element3.GetAttribute("style.cssText");
return Element4.GetAttribute("style.fontWeight")

I am getting null. When I view the DOM/properties of the elements above, I do see the values that they have.

cssText: "font-weight: bold;"
fontWeight: "bold"

If I right click on the properties from within the Developer Toolbar and choose "Copy Property Path", I get the following:

style.cssText
style.fontWeight    

So I believe the problem is how I am referring to the child property by assuming what I am copying from the developer toolbar is correct. I have tried other delimiters other than a period, but I am still having now luck.

I'm trying to figure out the syntax to return the value stored in -

object.style.fontWeight

I've tried:

parent.child.GetCSSValue("css"), parent-child.GetCSSValue("css")
parent.child.GetAttribute("attrib"), parent-child.GetAttribute("attrib")
parent.child.GetProperty("prop"), parent-child.GetProperty("prop")

These all come back as null or empty.string


Solution

  • Seems you were pretty close. To retrieve the cssText and fontWeight you can use the getComputedStyle() and then use getPropertyValue() to retrieve the style and you can use the following solution:

    IJavascriptExecutor jse = (IJavascriptExecutor)driver;
    String cssText_script = "var x = getComputedStyle(arguments[0]);" +
            "window.document.defaultView.getComputedStyle(x,null).getPropertyValue('cssText');"; ";
    String fontWeight_script = "var x = getComputedStyle(arguments[0]);" +
            "window.document.defaultView.getComputedStyle(x,null).getPropertyValue('fontWeight');"; ";
    string myCssText = (string) jse.ExecuteScript(cssText_script, Element3);
    string myFontWeight = (string) jse.ExecuteScript(fontWeight_script, Element4);
    

    Note: You need to induce WebDriverWait along with the ExpectedConditions as ElementIsVisible method.