views:

213

answers:

3

HTML:

<div class="parent">
    <div class="one"></div>
    <div class="two"></div>
    <div class="three"></div>
</div>

jQuery

parentWidth = $(".parent").outerWidth(true);
oneWidth = $(".parent .one").outerWidth(true);
twoWidth = $(".parent .two").outerWidth(true);
$('.parent .three').width( parentWidth - oneWidth - twoWidth);

But the thing is, either DIV .one or .two may not exist some times, how do I modify the jQuery for it?

Thanks

+3  A: 

Why don't you just check whether the result of $ function is empty ? ;) That way you can easily find out whether the div exists and simply set the width to 0 in that case, e.g.

oneDiv = $(".parent .one");
oneWidth = oneDiv.length == 0 ? 0 : oneDiv.outerWidth(true);
Thomas Wanner
`$(selector)` will never give you `null`. If there is no matching element you will simply get an empty list wrapper. You would need to check eg. `$('.parent .one').length`.
bobince
Thank you for pointing that out, I'll fix it. I am actually coming from the world of Prototype where the $ gives you null for non-existing element.
Thomas Wanner
+2  A: 

You can check if an element exists by checking its length property:

parentWidth = $(".parent").outerWidth(true);
oneWidth = $(".parent .one").length ? $(".parent .one").outerWidth(true):0;
twoWidth = $(".parent .two").length ? $(".parent .two").outerWidth(true):0;
$('.parent .three').width( parentWidth - oneWidth - twoWidth);
John McCollum
Perfect, thanks heaps! :)
Nimbuz
You're welcome :)
John McCollum
-1 for non-systematic approach and for violation of the DRY principle.
Anton
Thanks for explaining your downvote, I agree it's not the most elegant solution.
John McCollum
+2  A: 

Try this code:

var third = $('.parent .three');
var wantedWidth = third.parent().outerWidth(true);

third.siblings().each(function(){
    wantedWidth -= $(this).outerWidth(true);
});

third.width(wantedWidth);
Anton