Robert Robert - 6 months ago 19
HTML Question

Javascript not returning style properties

I have a simple script that is getting the color of the text in an element and printing it to the console. However, when I run the script, I'm getting an empty string rather than the actual color. Can anyone explain to me why and how to fix it?

HTML

<div id="scrollingTextHolder">
<p id="scrollingText">Hello</p>
</div>


CSS

#scrollingText{
margin-top: 5%;
color: black;
}


JS

window.addEventListener("load", function(){
console.log(document.getElementById("scrollingText").style.color);
})


Pen

Answer

You can use getComputedStyle() and getPropertyValue(), also color is returned as rgb(R,G,B)

var a = document.getElementById("scrollingText");
console.log(window.getComputedStyle(a).getPropertyValue('color'))
#scrollingText {
  margin-top: 5%;
  color: black;
}
<div id="scrollingTextHolder">
  <p id="scrollingText">Hello</p>
</div>

Comments