0

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;

angular.element(document.getElementById("box")).css("width")

It's not worked. After, i tried like this;

document.getElementById("box").style

But it's not worked. How can i accomplish this?

3
  • It could be because you are searching for an element that is not loaded in the DOM yet. Try to add your code inside, angular.element(document).ready(function () { document.getElementById("box").style }); Commented Oct 30, 2017 at 21:02
  • 1
    document.getElementById("box").style.width is what you are loooking for Commented Oct 30, 2017 at 21:05
  • I can't use 'ready function', because i don't use jquery. @PraveenAlluri Commented Oct 30, 2017 at 21:10

2 Answers 2

3

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}
<div id="a" style="width: 100px">A</div>
<div id="b">B</div>

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.