Reputation: 55
i have a question about to get the X id by document.getElementById("X").style.backgroundColor this is my HTML:
<div id ="X" class="main-sidebar text-white ">
</div>
CSS like:
.main-sidebar{
background-color: #343a40;
width:10%;
height:100%;
display:block;
position: absolute;
left:0px;
/*top:0px;*/
}
But when I use document.getElementById("X").style.backgroundColor in js i get NULL value...
Upvotes: 0
Views: 1183
Reputation: 2682
That's because style
refers to the inline style
attribute in your HTML. If you want to get the style
that's set via CSS only, you will need to use computedStyles
.
const elem = document.getElementsByTagName('p')[0]; // get element
const styles = window.getComputedStyle(elem); // get computed style of element
console.log(styles.getPropertyValue('background-color')); // get specific attribute
p {
background-color: red;
}
<p>Hi!</p>
Upvotes: 5
Reputation: 2366
.style
Will get or set the inline style of an element.
In your case, the style for .main-sidebar
is in a .css file.
What you can do is use getComputedStyle()
:
getComputedStyle(document.getElementById("X")).backgroundColor // #343a40
Upvotes: 1
Reputation: 23360
Try using computed styles:
window.getComputedStyle(document.getElementById("X")).backgroundColor
Upvotes: 1