Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate width dynamically (jQuery)

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

like image 696
eozzy Avatar asked Jul 23 '26 04:07

eozzy


1 Answers

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);
like image 105
John McCollum Avatar answered Jul 25 '26 17:07

John McCollum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!