0

Get css style property values?

I obviously dont know enough about CSS and how to interact with it via JS, but before I go learn my way down another rabbithole, I'd like to play with this animation. I want to get the 200px value associated with #container{width: 200px ...} and store it in cW. I tried : var cW = document.getElementById('container').style.width; alert(cW); in JS but the alert was undefined. I also tried a few variations on that statement. What is the proper way to get that value? Thanks. EDIT: link to code below https://code.sololearn.com/WpdzM0YcqUNu/?ref=app

25th Sep 2018, 5:26 AM
Beau Sterling
Beau Sterling - avatar
8 odpowiedzi
+ 2
had to do some learning afterall. i used : var cont = document.getElementById('container'); var style = window.getComputedStyle(cont); var cW = style.getPropertyValue('width'); alert(cW); and it worked. not sure if its poor etiquette to post external resources but the code i used was adapted from https://stackoverflow.com/questions/6338217/get-a-css-value-with-javascript
25th Sep 2018, 6:09 AM
Beau Sterling
Beau Sterling - avatar
+ 3
var cont = document.getElementById('container'); var cW = cont.offsetWidth; .css is a jQuery function.
25th Sep 2018, 6:19 AM
Calviղ
Calviղ - avatar
+ 2
It's better to provide a link to the Code Playground project to properly diagnose, but it is most likely an issue with the order in which things are executed rather than an issue with the individual instruction. If you try to run the scripts before the document has loaded, it won't know where #container is. If you wrap your instructions in a function and defer it (e.g. window.onload) then it should be able to find #container.
25th Sep 2018, 5:37 AM
Janning⭐
Janning⭐ - avatar
+ 1
thanks for your help. i inserted a link into my post.
25th Sep 2018, 5:46 AM
Beau Sterling
Beau Sterling - avatar
+ 1
try using css instead of style in the selector
25th Sep 2018, 5:50 AM
Manual
Manual - avatar
0
it didnt like ...').css.width; It gave me a Type Error. But I may have mis-executed your instruction
25th Sep 2018, 5:55 AM
Beau Sterling
Beau Sterling - avatar
0
that's much more compact and it returns an int so i don't have to parse it. thanks!
25th Sep 2018, 6:23 AM
Beau Sterling
Beau Sterling - avatar
0
one of these days I'll learn what jQuery means.
25th Sep 2018, 6:24 AM
Beau Sterling
Beau Sterling - avatar