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
8 Réponses
+ 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
+ 3
var cont = document.getElementById('container');
var cW = cont.offsetWidth;
.css is a jQuery function.
+ 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.
+ 1
thanks for your help. i inserted a link into my post.
+ 1
try using css instead of style in the selector
0
it didnt like ...').css.width; It gave me a Type Error. But I may have mis-executed your instruction
0
that's much more compact and it returns an int so i don't have to parse it. thanks!
0
one of these days I'll learn what jQuery means.