How to use jQuery to retrieve the height of the elements inside a specific container

I'm uncertain if it's feasible, but I am looking to determine the total height of the content within a specific container. Imagine I have

<div id="container" style="min-height:100vh">
    <div class="child">
      <p>Some text here</p>
    </div>
    <div class="another-child">
      <p>Some text here</p>
    </div>
</div>

How can I accurately find the height of the content within #container? The inline heights provided are just samples to illustrate that the parent height could vary. I am interested in knowing the actual space occupied by the content. This is considering that there may be numerous child elements within the container.

Please note: In the example above, the true height refers to the combined height of those paragraphs if they were not displayed inline.

Answer №1

Unsure if achieving this with a single jQuery/javascript function is possible, but here's a snippet that could prove helpful

HTML

 // A common class has been added to all child elements of div#container
     <div id="container" style="min-height:100vh">
        <div class="child cc">
          <p>Some </br>text here</p>
        </div>
        <div class="another-child cc">
          <p>Some text here</p>
        </div>
    </div>

JS

// Iterating through all child elements using a common class to calculate total height
var cc = 0;
    $("#container > div.cc").each(function(){
        cc += $(this).outerHeight();
    });
$('#height').append('<p>'+ cc+'</p>' );

CSS

 p{
    margin:0px;
        }

Check here for more information on why setting margin:0

View JSFIDDLE

UPDATE

Incorporated an iterator to exclude inline elements. Also, the .each now iterates over elements with the cc class. This allows inline elements to be excluded from having the cc class.

Below is a code snippet to check the display type of an element before calculating its height.

var cc = 0;
    $("#container > .cc").each(function(){
      var getDisplay = $(this).attr('dipslay') // Check the display attribute
       // Using ternary operator 
       getDisplay !=='inline'? (cc += $(this).outerHeight()) :0;
     });

VIEW UPDATED FIDDLE

Answer №2

One possible solution is to try using the code snippet below:

console.log(window.getComputedStyle($("#container")[0]).getPropertyValue("height"))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div id="container" style="min-height:100vh">
  <div class="child" style="height:100%">
    <div class="another-child">
      <p>Some text here</p>
    </div>
    <div class="another-child">
      <p>Some text here</p>
    </div>
  </div>
</div>

Answer №3

If you want to determine the height of an element using jQuery, you have a few options:

$('#wrapper').height();

This will give you the current computed height of the first matched element.

You can also use:

$('#wrapper').innerHeight();

Which returns the inner height (including padding but not border) of the first matched element.

Alternatively, you can try:

$('#wrapper').outerHeight();

This will provide you with the outer height (including padding, border, and optionally margin) of the first matched element.


Check out a demo here!

Answer №4

To determine the height of your container using jQuery, you can utilize the following method: $("selector").height(); This code will provide you with the exact dimensions of your container.

Answer №5


var counter = 0;
$("#"+currentID2c+ "> .cc").each(function(){
    var displayValue = $(this).attr('display');
    if(displayValue !== 'inline') {
        counter += $(this).outerHeight();
    } else {
        counter += 0;
    }
});
var total = counter;
console.log(total);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for integrating React into a jQuery-centric web application?

After diving into React, I'm eager to showcase my skills by implementing it on select pages as a proof-of-concept for my supervisor at work. Can anyone guide me on how to achieve this using traditional script tags instead of imports? So far, I'v ...

How to access a bootstrap 4 tab panel on a different page

How can I successfully open a specific tab panel on the service.html page when clicking a link on my index page? I'm using bootstrap nav-pills and have tried the following, which unfortunately did not work as expected: service.html <div class="na ...

Hover Effect in JavaScript

After thoroughly checking all the duplicates below, I still couldn't quite figure out how to achieve the desired effect. Here are some resources I looked into: make animation hover like transition hover JS hover-like animation Hover animation with js ...

Changing Location of Carousel in Bootstrap

Recently, I have been working with Bootstrap and have encountered a problem with the carousel. I have placed carousel images below my navbar, but there seems to be a gap between the navbar and the carousel image. I want the image to be right below the navb ...

Photos failing to load in the image slider

Although it may seem intimidating, a large portion of the code is repetitive. Experiment by clicking on the red buttons. <body> <ul id="carousel" class="carousel"> <button id="moveSlideLeft" class="moveSlide moveSlideLeft"></button& ...

Troubleshooting AngularJS POST Request Error with Request Body

I am a beginner in AngularJs and I am trying to make a post request to a server with enum form. Currently, I have the following JavaScript code: function completeTaskAction2($scope, $http, Base64) { $http.defaults.headers.common['Authorization'] ...

ErrorMessage: Found an unexpected character '{' while parsing the jQuery DataTables code

I've been attempting to incorporate the datatable library into my code, but I'm consistently encountering a SyntaxError: Unexpected token '{' in the javascript console. Even after searching for a solution online, it appears that my jav ...

Combine multiple values into a single input in the number field

I have a number type input field... What I am looking for is: Age-Height-Weight 20-180-80 Is there a way to ensure that users input data in this exact format and then have the final result inserted into the input field with type="number" and submitted? ...

trouble combining two arrays of JavaScript objects

I'm facing a challenge with an object array. I need to add a new object "WITH" a specific index, but I'm unsure of the correct approach. This is my current attempt: //ORIGINAL DATA: this.fetchedData = [{ "startMinute": 0, //Remove "annotati ...

ReactJS component state fails to update accurately

Let's say I have a component named Test import {useEffect, useState} from "react"; const Test = (props) => { const [Amount, setAmount] = useState(1); useEffect(()=>{ if(props.defaultAmount){ setAmount(prop ...

How to extract only the truthy keys from an object using Angular.js

I am looking to retrieve only the keys with a true value in the data object and display them in the console with the specified format: Object { Agent=true, Analytics / Business Intelligence=true, Architecture / Interior Design=false } The catego ...

Angular's Enhanced Feature: Selecting Multiple Columns

Looking for an open-source Angular library that can display items in multiple columns rather than each item spanning across multiple columns. Many libraries support tabular display, but the challenge is to find one that arranges items in multiple columns. ...

Attempting to align a navigation block next to an SVG image

On my website, I envisioned a photoshopped image featuring a SVG picture of a book on the left and a "navigation block" on the right. The navigation block consists of links that redirect to other pages but it's not displaying properly. You can view th ...

Javascript tabs with clickable links

I have created a page with a series of thumbnails that reveal content below when clicked. The content is positioned absolutely and set to display:none, with javascript changing this for each thumbnail. (I am not very familiar with javascript and learned t ...

Experiencing difficulty with MIME type and serialization while sending JSON data using JQuery

Currently, I am attempting to send some JSON data via a POST request to a web service that requires JSON. The function 'basistech.serializeOptions()' currently returns a JavaScript object, however, it could easily be modified to return a string ...

CSS tilt effect for images

I'm currently working on a project where I have two images stacked on top of each other. Using CSS transformations, I want to create a flip effect by first rotating both images away and then bringing the bottom image back in. However, I'm facing ...

Determine the cumulative and present slide count on the Bootstrap slider

Using JavaScript and Bootstrap controls, you can easily track the number of slides in a standard Bootstrap carousel. By implementing a simple button press counter that increments or decrements, you can keep track of the total and current slide numbers usin ...

Storing a collection of strings in a MongoDB database: A step-by-step guide

I have come across a few similar questions on stack overflow like this one: How to store an array of Strings in Node MongoDB Mongoose - Save array of strings However, I am unable to understand why my method is not working. I am attempting to save the str ...

The width of a <div> element in CSS is not dependent on the width

Is there a way to make tables within a div have relative widths to each other? For example, if one table has a large image or long word causing it to extend to 100%, how can we ensure that the other tables in the same div also adjust to 100% width? CSS . ...

Utilizing the SmartSuggest jQuery plugin for seamless integration of JSON data

Recently, I acquired the jquery plugin named smart suggest and I am interested in feeding a json array as opposed to just an array. The existing data file, 'sample-data.php', displays: <?php $fruits = '{...}'; $vegetables = '{ ...