Home > Net >  Copy divs height and apply it to an other div with Javascript
Copy divs height and apply it to an other div with Javascript

Time:09-28

<div class="thisOne">
</div>

<div class="thisHeight">
</div>

I want to copy thisHeight divs height and apply it to thisOne div, so as the result this two divs will always have the same height.

CodePudding user response:

  1. find that element
  2. get its offsetheight
  3. find the other element
  4. set its height
const elem = document.querySelector(`.thisHeight`);
const elemHeight = elem.offsetHeight;
const secondElem = document.querySelector(`.thisOne `);
secondElem.style.height = elemHeight;

CodePudding user response:

You can apply more than one CSS to a single div as follows (by separating with a single space in between):

<div class="thisOne thisHeight">
</div>

This will copy all the styling in thisHeight so if you want to just use the height, you should separate it out into a separate style.

<style>
thisOne {... }

thisOneHeight {... }

myHeight {
     height : 100px;
          }
</style>

<body>

<div class="thisOne myHeight"></div>

<div class="thisHeight myHeight"></div>

</body>

CodePudding user response:

you can do the following in javascript:

 const height = document.getElementsByClassName('thisHeight')[0].offsetHeight;
 document.getElementsByClassName('thisOne')[0].style.height = `${height}px`;

I don't know what your endgoal is, but I would suggest taking a look at flexbox to have a CSS only solution.

information can be found here: https://css-tricks.com/snippets/css/a-guide-to-flexbox/

CodePudding user response:

you probably looking for .getBoundingClientRect() function to get computed height and width of an element

var thisHeight = document.querySelector(".thisHeight"),
    thisOne = document.querySelector(".thisOne")
    
function copyHeight(from,to){
    to.style.height = from.getBoundingClientRect().height   "px"
}

copyHeight(thisHeight,thisOne)
.border {border:1px solid gray;}
<div class="thisOne border">
    copied height
</div>

<div class="thisHeight border">
    Lorem ipsum dolor sit amet consectetur adipisicing elit. Nulla maxime pariatur quia libero vitae blanditiis velit temporibus? Esse modi perspiciatis consectetur eius nihil magnam, quaerat, dignissimos nisi unde quas quod!
</div>

  • Related