Home > Blockchain >  How can you the return the largest Height value out of multiple divs using jQuery or JavaScript
How can you the return the largest Height value out of multiple divs using jQuery or JavaScript

Time:12-19

I am trying to return / output the largest Height value out of multiple divs within an alert using jQuery or JavaScript. I've tried a few examples but I think I'm going about it the wrong way. I decided to use Math.max but I think that incorrect. Also, I would like to only return the highest value of the div that is visible.

So overall I'd like to return the height value of the tallest div where visibility: visible

My code

    $(".go-buttn").click(function(){
        var sum = 0;
        var x = document.querySelectorAll(".block div");
        var maxValueInArray = Math.max.apply(Math, x);
        alert($(maxValueInArray).height());
    });


    <button >Click me </button>


<div >
    <div style="visibility:visible;"> //This first div should return the tallest value in height
        <p>
        test 
        </p>
        <p>
        test 
        </p>
        <p>
        test 
        </p>
    </div>


    <div> //Although This Div is taller than the first div this div is set to visibility hidden so we should not return this height value
        <p>
       test
       </p>

        <p>
        test 
        </p>
        <p>
        test 
        </p>
        <p>
        test 
        </p>
    </div>

    <div style="style="visibility:visible;">
        <p>
        Test  
        </p>
    </div>

    <div style="visibility:hidden;>
        <p>
        Test  
        </p>
    </div>
</div>

UPDATE I made changes based off of suggestions to the code below but I'm still not able to display only the tallest div that is visible.

        $(".go-buttn").click(function(){
            var x = Array.from(document.querySelectorAll(" .block div")).map(e => $(e).outerHeight());
            var maxValueInArray = Math.max.apply(Math, x);
            
            $('.dealer:visible').css('height',maxValueInArray);
            

        });

CodePudding user response:

const divs = document.querySelectorAll("p");
let max = 0;

divs.forEach((div)=> {
    if(div.offsetHeight > max)
        max = div.offsetHeight;
});

console.log(max);

CodePudding user response:

Here is a JQuery answer to your question:

Using a state approach

$(() => {
  // console.debug("Document ready...");
  // register the click function
  $(".go-button").click(function(){
    // using a state
    let currentMax = 0;
    // loop through each element
    $(".block p:visible").each((index, el) => {
      // update the state if current element's height is larger
      currentMax = Math.max($(el).height(), currentMax);
      console.debug(`Current element's height: ${$(el).height()}`);
    })
    console.log(`Max height is ${currentMax}`);
  });
});

As you had attempted using the "Math.max" variant for array, the solution can also be condensed into a single-liner using the "map" function.

The one-liner approach

$(() => {
  // console.debug("Document ready...");
  $(".go-button").click(function(){
    const currentMax = Math.max(...$(".block p:visible").map((index, el) => $(el).height()))
    console.log(`Max height is ${currentMax}`);
  });
});

The state approach tends to be easier for other developers to read and to extend functionality later, such as if you need to do other things with the element other than need logging the state. But if the numeric result is all that's needed, there is arguably less code to read with the one-liner so long as it has appropriate namings.

Here's a snippet with p tag of different height to test out the code: https://codepen.io/gordonso/pen/LYzLGzz?editors=1111

Update: upon re-reading the question, there is a specific requirement about the visible element's height. As such, the selector will need to be "$(".block p:visible")" to exclude elements with "hidden" attribute.

There are certain assumptions made in JQuery about visiblity selector, documented here: https://api.jquery.com/visible-selector/

CodePudding user response:

apply takes an array as its second parameter

The way you're using it, I assume you would want to pass in an array of the heights.

var x = Array.from(document.querySelectorAll(".col-lg-6.col-md-12.col-sm-12 .block")).map(e => $(e).height());
var maxValueInArray = Math.max.apply(Math, x);
alert(maxValueInArray);

If you need the actual element, not just the maximum height, you can sort the array and get the first value:

var x = Array.from(document.querySelectorAll(".col-lg-6.col-md-12.col-sm-12 .block"));
var maxValueInArray = x.sort((a,b) => $(b).height() - $(a).height())[0];
alert($(maxValueInArray).height());

Answer to updated question:

You can use display:none instead of visibility:hidden and the element's height will collapse to zero.

Or, if you need to use visibility, just check within the map function before returning each element's height:

var x = Array.from(document.querySelectorAll(".col-lg-6.col-md-12.col-sm-12 .block")).map(e => $(e).css("visibility") !== "hidden" ? $(e).height() : -1);
  • Related