pbaldauf pbaldauf - 1 year ago 116
jQuery Question

JavaScript convert NULL to 0

I'm using jQuery to get the height of an element.
But if the element doesn't exist, the following code will return NULL:

$height = $('#menu li.active ul').height(); // returns integer or null

Is it a cross-browser safe way for getting an integer value under every circumstance with the following code:

$height = $('#menu li.active ul').height() + 0;

Answer Source

There are many ways to deal with this. The one you describe, adding an integer value to coerce the type is fine. You could also convert to a number explicitly:

$height = Number($('#menu li.active ul').height());
// or:
$height = +$('#menu li.active ul').height();

Or you could use a logical operator as null coerces to false:

$height = $('#menu li.active ul').height() || 0;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download