Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the width of a div when width set by css class

Tags:

jquery

This JS script gives me an alertbox saying;

jQuery.UI.version = 1.0.2  ---   Box Width: undefined

How can I select the #resizable?

 <head>
    <title></title>
    <link href="StyleSheet.css" rel="stylesheet" type="text/css" />
    <script src="jquery-1.9.1.min.js" type="text/javascript"></script>
    <script src="jquery-ui-1.10.2.custom.min.js" type="text/javascript"></script>
       <style>
  #resizable { width: 200px; height: 150px; padding: 5px; border: 1px solid red;}

  </style>

      <script>
        $(function () {
            var boxWidth = $('#resizable').attr('width');
            alert("jQuery.UI.version = " + jQuery.ui.version + "  ---   Box Width: " + boxWidth);           
        });
  </script>


</head>
<body>
    <div id="resizable" class=">
        <div id="title">
            <h2>
            The expanding box
            </h2>
        </div>    
    </div>
</body>
like image 595
Daarwin Avatar asked Feb 17 '23 20:02

Daarwin


2 Answers

See here you don't have a attribute of width:

<div id="resizable" class=">

this will surely crash and set to undefined, var boxWidth = $('#resizable').attr('width');

There are two ways getting the width of an element like:

By the .width() way:

$('#resizable').width();

and by .css() way:

$('#resizable').css('width');
like image 65
Jai Avatar answered Feb 19 '23 11:02

Jai


your selector $('#resizable').attr('width'); search for attribute width in resizable which does not exists

i think you are asking for width()

try this

 var boxWidth = $('#resizable').width(); //this gives you the width of resizable div

updated seeing comment

your code reads the attribute width of div <div id="resizable" class="asd"> ..but see , there is no attribute called width in this div so it fails... doc to read more about attr()

your code will work if you add width in div like <div id="resizable" class="asd" width="30px">...this will give you 30px as alert...

like image 40
bipen Avatar answered Feb 19 '23 10:02

bipen