Skip to content Skip to sidebar Skip to footer

Getting Style Of An Element From Css File With Javascript

I wanna get a style of an element from css file with javascript. But, i just can getting only elements i enter style properties on javascript. I tried like this on Angular; angula

Solution 1:

This isn't an Angular issue, it's just how CSS and Javascript interact. You need to use getComputedStyle to read style properties that were defined in a CSS file.

// This will work (because it's an inline style)console.log(document.getElementById('a').style.width)

// This won't work (because the style was defined in css):console.log(document.getElementById('b').style.width)

// getComputedStyle will work regardless of the source:console.log(window.getComputedStyle(document.getElementById('b')).width)
#b {width: 100px}
<divid="a"style="width: 100px">A</div><divid="b">B</div>

Solution 2:

You cannot get css template rule values of elements calling style properties unless they were set *1. using inline style on html element level; or *2. the style property has been set using JavaScript

which does the same: writes to inline html style property of the target element.

the solution is to use the computed style instead:

as in : getComputedStyle(box,0).width

Post a Comment for "Getting Style Of An Element From Css File With Javascript"