I am trying to get the background color of the body element and the text color of the button element after clicking on the button.
HTML code:
<html>
<head>
<style>
#container
{
width: 100px;
height: 100px;
border: 1px solid #ccc;
overflow-x: scroll;
}
#content
{
margin:4px, 4px;
padding:4px;
width: 500px;
height:500px;
text-align:justify;
background-color: #ccc;
}
</style>
</head>
<body>
<div id="container">
<div id="content">Click the button to slide right!</div>
</div>
<button id="slide" type="button" onclick="dem_func()">Slide right</button>
<script>
function dem_func()
{
document.getElementById('container').scrollLeft += 50;
<!-- Changing the text color of button element-->
document.getElementById('slide').style.color='red'
<!-- Changing the background color of body element-->
document.body.style.backgroundColor='yellow'
return document.getElementById('slide').style.color
}
</script>
</body>
</html>
Working of the HTML code: After clicking on the button, the background color of the body of the page changes to yellow and the text color of the button changes to red as per the Javascript function. Also, the style attribute gets appended inline to the body and button element in the DOM as shown below:
<body style="background-color: yellow;">
<div id="container">
<div id="content">Click the button to slide right!</div>
</div>
<button id="slide" type="button" onclick="dem_func()" style="color: red;">Slide right</button>
Selenium code:
String color1 = driver.findElement(By.xpath("child::html/child::body")).getAttribute("background-color");
System.out.println("Color of the background of body element: " + color1);
String color2 = driver.findElement(By.xpath("//button")).getAttribute("color");
System.out.println("Color of the text of button element: " + color2);
As per the Selenium doc for getAttribute() method:
Get the value of the given attribute of the element. Will return the current value, even if this has been modified after the page has been loaded. More exactly, this method will return the value of the property with the given name, if it exists. If it does not, then the value of the attribute with the given name is returned. If neither exists, null is returned.
But here it returns null for both color1 and color2.
I want to understand why the getAttribute method returns null.
color
isn't an attribute of the element. It's part of thestyle
attribute's value.<p color="red">I am red</p>
and expect the text to actually be red unless you have the actual CSS rule for[color="red"] { color: red; }
.