0

I have code like this :

HTML:

<div id="myDiv" class="container">
  ....
</div>

CSS:

div.container {
    width: 300px;
    height: 400px;
    border: solid 1px black;
    overflow: hidden;
    background:  #efefef;
}

JS:

var myDiv = document.getElementById("myDiv");
var pageWidth = parseInt(myDiv.style.width);

I want to read css property and I can change value using js.
I have tried search with google, and my js code from link of google.
After I check the problem with safari's web inspector, there is problem in that I give sign for js code. Why is that wrong?

dfsq
  • 191,768
  • 25
  • 236
  • 258
yozawiratama
  • 4,209
  • 12
  • 58
  • 106
  • The `style` JavaScript property only knows about CSS specified in the element's `style` HTML property, *not* to CSS specified in a stylesheet provided through a ` – apsillers Apr 03 '13 at 13:30

5 Answers5

0

You probably want to use css:

$("#myDiv").css("width","yourWidthhere");

To get the width of an element, just use:

$("#yourElementId").width();
Eli
  • 14,779
  • 5
  • 59
  • 77
0
var width = parseInt($('#myDiv').width(), 10);
Spokey
  • 10,974
  • 2
  • 28
  • 44
  • No need to parse a returned `Number` value, cause `.width()` will not return extra string characters. And when you use `parseInt` use it with a (in this case decimal `10`) radix value `parseInt(value, radix);` – Roko C. Buljan Apr 03 '13 at 13:37
0

try this

alert($('yourdiv').width());

live demo here

IT ppl
  • 2,626
  • 1
  • 39
  • 56
0

You may try this :

$("#myDiv").css("width","100%");
ravisolanki07
  • 637
  • 3
  • 13
0

You can't get the class property using this code.

var myDiv = document.getElementById("myDiv"); var pageWidth = parseInt(myDiv.style.width);

I am going with a jquery way, here is the sample code:

<html>
    <head>
        <style>
            div.container { width: 300px; height: 400px; border: solid 1px black; overflow: hidden; background:  #efefef;}
        </style>    
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js" type="text/javascript"></script>
    </head>
    <body><div id="myDiv" class="container"> hi...</div></body>
</html>

Then you should able to get and set the width using the jquery methods:

$("#myDiv").width(); //Get $("#myDiv").width(500); //Set

VSV
  • 11
  • 4