-3

I have an object (div) which has four elements (with classes) inside.

Task: When height of the element A is lower than 40px then add to element B 20px margin-top.

However there are many objects on the page.

<div class="list">
<div class="block">
  <div class="list-name" style="height: 20px">element A</div>
  <div class="div1">another div here</div>
  <div class="div2">another div here</div>
  <div class="product-image-container">element B</div>
</div>

<div class="block">
  <div class="list-name" style="height: 50px">element A</div>
  <div class="div1">another div here</div>
  <div class="div2">another div here</div>
  <div class="product-image-container">element B</div>
</div>

(...)

</div>

Sorry, I tried this so far. However it works only if there are only two elements in the div.

$(document).ready(function(){
    $('.list-name').each(function(index, obj){
    console.log($(obj).height())
    if($(obj).height() < 40)
    {
       $(obj).next('.product-image-container').css('margin-top', 20)
    }
    });


});

Thanks for any help.

Rob

Rob
  • 7
  • 2
  • 1
    [StackOverflow isn't here to do your work for you](https://stackoverflow.com/help/on-topic). Show us what you have tried so far. We'll gladly help you. – Zenoo Apr 18 '18 at 07:59

1 Answers1

0

As far as I understand, you need something like this:

var heightA = $(".list-name").css("height"); //get height of element. E.g. "20px"
heightA = heightA.substr(0, heightA.length - 2); //remove "px" from string => "20"
if (heightA < 40) { //if the height is less than 40
    $(".product-image-container").css("margin-top", "20px"); //add margin-top 20px
}

To do this for all elements, you will need a for. Maybe try this:

var elements = $("body div").length; //get amount of divs. In the HTML you provided 'body' is the parent
for (i = 0; i < elements; i++) { //loop 'em all
    var heightA = $("div:nth-child(" + i + ") .list-name").css("height"); //again get height of corresponding element
    heightA = heightA.substr(0, heightA.length - 2); //remove "px"
    if (heightA < 40) {
        $("div:nth-child(" + i + ") .product-image-container").css("margin-top", "20px"); //set margin-top of corresponding element
    }
}
undefined
  • 1,019
  • 12
  • 24
  • The style I mean height of element A is automatically generated. The styles I wrote "height: 20px" and "height: 50px" were just as an example. Do not know if that is the reason why is the code not working. – Rob Apr 18 '18 at 13:40
  • I also tried to change .css("height") to .height() but it did not help. – Rob Apr 18 '18 at 13:46
  • @Rob, maybe try this: https://stackoverflow.com/questions/526347/how-do-you-get-the-rendered-height-of-an-element – undefined Apr 18 '18 at 14:32