Hunter Hodnett
Hunter Hodnett

Reputation: 347

Best method of dynamically setting the height of an DOM element with JQuery?

I've used both $('#element').css('height', 10) and $('#element').height(10). Which method is the better practice? Or do they both change the height in the exact same way?

Upvotes: 2

Views: 207

Answers (4)

Joe_G
Joe_G

Reputation: 906

It looks like there isn't a monumental difference besides the fact that you need to specify 'px' for css(). Like m90 said in the comments (and as you can see in the fiddle they posted), each is affected differently by the border-box property (css() takes the padding into account and includes it in the height while height() does not), so this should also be taken into account when deciding which to use.

The jQuery API also has this to say about height():

Note that .height(value) sets the content height of the box regardless of the 
value of the CSS box-sizing property.

In regards to speed, I found this: http://jsperf.com/jquery-css-height-vs-method-height/2

Here's another general link: http://jquerybyexample.blogspot.com/2010/08/width-vs-csswidth-and-height-vs.html

Upvotes: 1

m90
m90

Reputation: 11822

The difference is that with .css() you are just specifying the value of the inlined style property whereas height() tries to set the height of the box. From the docs:

Note that .height(value) sets the content height of the box regardless of the value of the CSS box-sizing property.

See this fiddle for a demonstration of the difference and also have a look at the relevant part of the source code

Upvotes: 2

Hamza Kubba
Hamza Kubba

Reputation: 2269

.height() is better between those two (as is), but only because .css() isn't supposed to take integers as parameters... it should be .css('height', '10px').

In general, I prefer to use .css() because I know exactly what it is going to do (set the element style), whereas .height() works in mysterious ways (even if simple, not immediately evident).

Additionally .css() allows you to set the height to '45%' or 'auto', whereas you can't accomplish those things with .height()

Upvotes: 1

Mohammad Masoudian
Mohammad Masoudian

Reputation: 3501

From the JQuery height() documentation :

The difference between .css('height') and .height() 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 .height() method is recommended when an element's height needs to be used in a mathematical calculation.

Upvotes: 0

Related Questions