jQuery .width()

jQuery .width() gets or sets width of the target element;

$(DOMElement).width(); // Element width

$(DOMElement).innerWidth(); // Element width + padding

$(DOMElement).outerWidth(); // Element width + padding + border

$(DOMElement).outerWidth(true); // Element width + padding + border + margin

Also check jQuery .height()

js:

1
2
3
4
5
6
7
8
9
10
11
12
13
$(function(){
 
    var target_width = $('.target').width(); // get target width
 
    $('.target2').width( target_width ); // set target width
 
    $('.target2 .width2 span').text( target_width );
 
    $('.innerWidth_log span').text( $('.target').innerWidth() );
 
    $('.outerWidth_log span').text( $('.target').outerWidth() );
 
});​

html:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<div class="well target">
 
    <span class="label label-warning">.target</span>
 
    <p>set in css:
 
        <span class="label label-info">width: 400px;</span>
 
        <span class="label label-info">padding: 10px;</span>
 
        <span class="label label-info">margin: 12px;</span>
 
        <span class="label label-info">border: 2px;</span>
 
    </p>
 
    <p>get values by
 
</div>
 
  
 
<div class="target2">
 
    <span class="label label-success width2">width:<span></span></span>
 
    <span>width of this block set by jQuery (same as prev block)</span>
 
</div>
 
 
 
<div class="well">
 
    get .target properties with jQuery:
 
    <span class="label label-success innerWidth_log">
 
        innerWidth: <span></span>
 
    </span>
 
     
 
    <span class="label label-success outerWidth_log">
 
        outerWidth: <span></span>
 
    </span>
 
     
 
</div>

css:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
.target {
 
    width:400px;
 
    padding:10px;
 
    margin:12px;
 
    border:2px solid #bbb;
 
}
 
 
 
.target2 {
 
    background: #ccc;
 
    margin:10px 0;
 
}

Leave a Comment