9

I am having trouble getting the width of an element defined in CSS. I figured out how to get the CSS rules using Javascript, but I can't access the width. Menu is fixed width that I defined in CSS using em.

I am trying to change the width of the div1 based on the browser window minus the fixed menu width.

Note: I already tried using style.width, but it returns a blank line in the console.

jsfiddle: http://jsfiddle.net/kj6pQ/

var div1 = document.createElement('div'), 
css = getMatchedCSSRules(document.getElementById('menu'));

console.log(css); //works but dont' konw how to access width

div1.style.width = window.innerWidth - <!-- menu width -->;

3 Answers 3

20

use 'offsetWidth' to access the menu's width

var div1 = document.createElement('div'), 
css = document.getElementById('menu').offsetWidth;

console.log(css);
div1.style.width = css + "px";
0
6

Use getComputedStyle:

var css = document.getElementById('menu');

console.log(window.getComputedStyle(css).width);​

http://jsfiddle.net/kj6pQ/6/

0
2

Try this way:

var width = window.getComputedStyle(document.getElementById("menu"), null).getPropertyValue("width");

Your Answer

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