Home > Blockchain >  Getting the height of a child div part not overfloating out of the parent div
Getting the height of a child div part not overfloating out of the parent div

Time:09-07

If I have a parent div with a certain height and a child div with a greater height, typing something like document.getElementById("#id).style.height would give me the whole height of the child. How do I get only the height of this part of the child div still in the parent div?

Thank you very much in advance for answers and excuse me, if I didn't use technically correct words.

CodePudding user response:

If I understand correctly, You can calculate :

remaining height in parent = bottom position of parent - top position of child

let parent = document.getElementById("parent")
let child = document.getElementById("child")
console.log(parent.getBoundingClientRect().bottom - child.getBoundingClientRect().top)
#parent{
  height: 300px;
  background-color: grey;
}
.some-element{
  height: 5px;
}
#child{
  background-color: orange;
  height: 500px;
}
<div ></div>
<div id="parent">
  <div ></div>
  <div id="child">Child</div><!-- 300 - 5 = 295px inside the parent-->
  <div ></div>
</div>
<div ></div>

CodePudding user response:

solution 1:

you can use .parentNode to get parent (if you don't have directly access to parent), then get height of parent, it have to be same as part of the child div still in the parent div, something like:

document.getElementById("#id).parentNode.style.height

solution 2: (this will work even if child div moved)

if access to parent is not the problem, you need a more accurate solution, you can get coordinate of parent and child, then with a little math you have exact part of child in parent div...

let parentCoord = document.getElementById('parentId').getBoundingClientRect();
let childCoord = document.getElementById('childId').getBoundingClientRect();
var left = Math.max(parentCoord.left, childCoord.left);
var right = Math.min(parentCoord.right, childCoord.right);
var top = Math.max(parentCoord.top, childCoord.top);
var bottom = Math.min(parentCoord.bottom, childCoord.bottom);

now you have exact coords of that part of child in parent div, if you need a width you can do a simple math:

var width = right - left;
var height = bottom - top;

if this is not what you need then we need a little more details about what you are trying to do... if this is, then enjoy codding...

  • Related