Ahmad
Ahmad

Reputation: 13406

How to set height of parent, dependent on height of selected element

I have a scenario where I want to find all elements with a certain class, and then I want to set the parent div's padding-bottom value as the sum of its current padding-bottom value + the height of the original div which matched the selector.

So say I have a structure like this:

<div class='A'>
    <div class='B'>
        <div class='C'>
            .........
        </div>
        <div class='D'>
            .........
        </div>
    </div>
    <div class='B'>
        <div class='C'>
            .........
        </div>
    </div>
    <div class='B'>
        <div class='C'>
            .........
        </div>
    </div>
    <div class='B'>
        <div class='D'>
            .........
        </div>
    </div>
</div>

I want to find all class D objects, and then I want to set the padding bottom value of their container class B, to the height of the class D object in question, plus whatever padding-bottom value that class B object currently has ..

  1. Note that all class D objects have different heights ..
  2. Every class B objects can only have a max of 1 class D object
  3. Every class B objects can only have a max of 1 class C object

What jQuery do I need to do the above ?

Upvotes: 1

Views: 75

Answers (3)

M K
M K

Reputation: 9416

This should the solution for the problem that you've described. But I think you've missed some details. (this code might be shortened to a one liner though)

$(function() { 'use strict';
    $('.A > .D').each(function() {
        var $D = $(this);
        var $B = $D.closest('.B');

        $B.css('padding-bottom', 
            $D.height() + parseInt($B.css('padding-bottom'))
        );
    });
});

In case you want to include the height of the .C elements too:

$(function() { 'use strict';
    $('.A > .D, .A > .C').each(function() {
        var $X = $(this);
        var $B = $X.closest('.B');

        $B.css('padding-bottom', 
            $X.height() + parseInt($B.css('padding-bottom'))
        );
    });
});

Upvotes: 0

sbonkosky
sbonkosky

Reputation: 2557

$(function(){
   $('div.D').each(function(index){
      var dHeight = $(this).height();
      var bPadding = $(this).parent().css('padding-bottom');
      var newPadding = parseInt(dHeight) + parseInt(bPadding);
      $(this).parent().css('padding-bottom', String(newPadding) + 'px');
   });
});

Upvotes: 0

King King
King King

Reputation: 63337

Try this:

$('.D').each(function(){
   $(this).parent().css("paddingBottom", "+=" + $(this).height() +"px");
});

Demo.

Upvotes: 1

Related Questions