skip to Main Content

I’m currently trying to find out and access the height of several div containers that have the same class "content".

My HTML code Looks like this:

 <div class = “main”>
        <div class="item">
          <div class = “content”>
            <p></p>
          </div>
        </div>   
        <div class="item">
          <div class = “content”>
            <p></p>
          </div>
        </div>
        <div class="item">
          <div class = “content”>
            <p></p>
          </div>
        </div>
   </div>

My JavaScript looks like this:

let allContents = document.querySelectorAll(".content");

let allItems = document.querySelectorAll(”.item”);

let heightOfContents = allContents.offsetHeight;

Unfortunately I have no success with this.

I also tried the following:

let heightOfContents = document.querySelector(".content").getBoundingClientRect().height;

which didn’t work either.

I am expecting to get on the console the heigt of each container and to use them for further calculations.

Would any of you have an idea how this could work?

Thanks in advance for the help.

2

Answers


  1. You attempted to get the height of a single container, try something like this instead:

    const containers = document.querySelectorAll(".content");
    let totalHeight = 0;
    containers.forEach((c) => (totalHeight += c.getBoundingClientRect().height));
    
    Login or Signup to reply.
  2. According to MDN, document.querySelectorAll(".content") returns a static (not live) NodeList representing a list of the document’s elements that match the specified group of selectors.

    You cannot get the offsetHeight on a list. You may loop through this node list to get each height for further calculation.

    const allContents = document.querySelectorAll(".content");
    const allItems = document.querySelectorAll(".item");
    
    const contentHeights = [];
    allContents.forEach(item => {
        contentHeights.push(item.offsetHeight)
    });
    
    const itemHeights = [];
    allItems.forEach(item => item => {
        itemHeights.push(item.offsetHeight)
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search