manx
manx

Reputation: 37

Calculate div width

I have html tree like this

<div class="parent">
  <div class="child-1">
  </div>
  <div child="child-2">
  </div>
</div>
<div class="parent">
  <div class="child-1">
  </div>
  <div child="child-2">
  </div>
</div>

I need to calculate "child-2" width equal to "parent" minus "child-1". For each parent div. I have something like this but not working property.

$("parent").each(function(){
  var all = $(this).width();
  var child = $(this).children("child-1").width();
  var good = all - child;
  $("child-2").width(good);
});

Can you help me with that?

Upvotes: 0

Views: 51

Answers (2)

Bhushan Kawadkar
Bhushan Kawadkar

Reputation: 28523

you need to make few correction in your html and script

  1. change child="child-2" to class="child-2"
  2. user dot . selector to get div element with class name like $('.parent')
  3. use $(this).find() to get the correct child element

$(function() {
  $(".parent").each(function() {
    var all = $(this).width();
    var child = $(this).find(".child-1").width();
    //console.log(all);
    //console.log(child);
    var good = all - child;
    //console.log(good);
    $(this).find(".child-2").width(good);
  });
})
.parent {
border: 1px solid red;
height:100px;
width: 100%;
}
.child-1 {
border: 1px solid green;
height:100px;
width: 60%;
}
.child-2 {
border: 1px solid blue;
height:100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="parent">
  <div class="child-1">child 1
  </div>
  <div class="child-2"> child 2
  </div>
</div>
<div class="parent">
  <div class="child-1"> child1
  </div>
  <div class="child-2">child2
  </div>
</div>

Upvotes: 4

ralbuquerque
ralbuquerque

Reputation: 43

You're missing the class selector which is a dot, try this:

$(".parent").each(function(){
  var all = $(this).width();
  var child = $(this).children(".child-1").width();
  var good = all - child;
  $(".child-2").width(good);
});

EDIT:

And like @Bhushan Kawadkar told, you need to change child to class:

<div class="parent">
  <div class="child-1">
  </div>
  <div class="child-2">
  </div>
</div>
<div class="parent">
  <div class="child-1">
  </div>
  <div class="child-2">
  </div>
</div>

Upvotes: 2

Related Questions