0

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?

1
  • try good=parseInt(all)-parseInt(child) Commented Nov 6, 2020 at 14:21

2 Answers 2

4

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>

Sign up to request clarification or add additional context in comments.

2 Comments

Thank You! Point 1 and 2, was mistake with writing here, in my code it is fine. Point 3 is that I made wrong. Thank You, now works perfect.
happy to help you :)
2

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> 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.