Is there a way to access an element's CSS properties that are set by a class name in JavaScript?
In the case of the first div element, I have applied a "red" class which sets its background color to red. However, when I try to access the div's backgroundColor property in JavaScript, I am unable to do so. What is the correct method to retrieve an element's backgroundColor using JavaScript when it is set by a CSS class?
window.onload = function() {
var div = document.querySelector('.red');
console.log(div.style.backgroundColor);
var div_2 = document.querySelector('div:nth-child(2)');
console.log(div_2.style.backgroundColor);
}
.red {
background: red;
}
div:nth-child(2) {
background: green;
}
<div class="red">
Element1
</div>
<div id="div1">
Element2
</div>
Thanks