0

I have an element, a div with ID homeColumnContain, which I need to set the height of based on one of its absolutely positioned children, an image element with an ID of homePictureID. My code looks like the following:

window.onload = function() {resizeColumns()};
window.onresize = function() {resizeColumns()};
function resizeColumns() {
  document.getElementById("homeColumnContain").style.height = document.getElementById("homePictureID").style.height;
}
<div id="homeColumnContain">
  <div class="homeColumn">
    <!-- content -->
  </div>
  <div class="homeColumn">
    <div id="slideContain">
      <img src="images/image.jpg" id="homePictureID"/>
      <!-- content -->
    </div>
  </div>
</div>

The code appears to do nothing. I've added listeners for both resizing the window and on window load, as these two events are when the height should be changed. I've tried moving my script around in the HTML document and this didn't work. I don't have a whole lot of formal training with JavaScript, so any feedback as to why this approach doesn't work would be great. I would prefer the solution to not divert to using jQuery.

Edit: I additionally tried some of the responses in the question that this was marked a duplicate of, and none of them solved my issue. Also, if relevant, I have a width defined in my homePictureID as 100%.

Alex Rummel
  • 153
  • 1
  • 11
  • Your image has no style properties, so you need to extract its height using another method. Read [this](https://stackoverflow.com/questions/526347/how-do-you-get-the-rendered-height-of-an-element) for further explanation – GalAbra Jun 21 '19 at 19:30

1 Answers1

1

Try this:

document.getElementById("homeColumnContain").style.height = `${document.getElementById("homePictureID").getBoundingClientRect().height}px`

The difference being that you haven't set a height style for the homePictureID element, but the actual node on the DOM can be examined for its rendered height.

Jeff Hechler
  • 285
  • 3
  • 16