Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between jQuery .width(), style.width, and jQuery .css('width')?

What is the difference between the values returned by .width() from jQuery, .css('width') from jQuery, and the .style.width attribute on a node?

I'm curious because, in trying to set the width of two table cells to be equal, the first two gave me the same wrong answer. What are they actually measuring, and why is it not the same as the value that I can see in the .style attribute when I view the element in a browser?

like image 966
ckersch Avatar asked Jul 05 '13 18:07

ckersch


2 Answers

From width official documentation

The difference between .css(width) and .width() is that the latter returns a unit-less pixel value (for example, 400) while the former returns a value with units intact (for example, 400px). The .width() method is recommended when an element's width needs to be used in a mathematical calculation.

I'd say there is no difference between .css('width') and .style.with as css() method is used to set style object properties.

The difference between .css('width') / .width() and .style.with is that jQuery methods get the computed style using window.getComputedStyle( elem, null ). This method is used to read the actual property after CSS and styles are applied.

like image 131
Claudio Redi Avatar answered Nov 13 '22 17:11

Claudio Redi


Complementing Claudio Redi's answer: see the difference live: http://jsfiddle.net/vovkss/kPXaB/

I've used cm units intentionally to demonstrate that the output of .css('width') may be converted to pixels (or other units), while .width() is always an integer value representing a number of pixels.

Note that .style.width only applies to inline styles.

  • HTML:

    <div id="mydivInlineStyle" style="width: 10cm"><b>Inline style:</b>
    </div>
    
    <div id="mydivExternalStylesheet"><b>External stylesheet:</b> 
    </div>
    
  • CSS:

    div { 
      width: 10cm; 
      border: 10px solid blue; padding: 11px; margin: 12px; 
      background: aqua; white-space: pre; 
    }
    
  • JS:

    $('div').each(function(){ 
      $(this).append(
        'jQuery width(): ' + $(this).width() + "\n" + 
        '.css(\'width\'): ' + $(this).css('width') + "\n" + 
        '.style.width: ' + this.style.width
      ); 
    });
    
  • Output:

    Inline style: 
      jQuery width(): 378 
      .css('width'): 378px 
      .style.width: 10cm
    
    External stylesheet: 
      jQuery width(): 378 
      .css('width'): 378px 
      .style.width: 
    
like image 21
Alex Shesterov Avatar answered Nov 13 '22 18:11

Alex Shesterov