jquery. how to get each siblings height?
Asked Answered
J

3

5

I think this is very easy question for someone who is more experienced in Jquery.

for example we have simple html page with a few divs, and 3 of them have the same css class 'sidebar'

Each of this 'sidebar' divs have different content and different height.

I need to compare this divs height and find the longest one.

I know how to realize comparing, but I do not know how in Jquery I can take each of this divs

to store their value in vairable or array.

Jerilynjeritah answered 16/7, 2010 at 3:56 Comment(2)
Are you specifying height of the div in sidebar class or is it explicitly given?Tragopan
no, I do not specify it in class.Jerilynjeritah
T
5
$.each($('.sidebar'), function() {
    var height = $(this).height();
});
Twist answered 16/7, 2010 at 4:5 Comment(3)
thank you! learning jquery, but sometimes it is difficult to do simple things, because I do not know all events and operators.Jerilynjeritah
You're welcome. When in doubt, use the jQuery documentation: api.jquery.comTwist
What's with using jQuery.each over plain old .each()? See my answer for links to the two.Episcopalian
E
13

I'm not sure why the two answers posted so far are using jQuery.each() rather than just calling each() directly, so here's what I would recommend:

$('#elementID').siblings().each(function ()
{
    var height = $(this).height();
});

To put each height into an array:

var heights = [];
$('#elementID').siblings().each(function ()
{
   heights.push($(this).height());
});

Or, just use map():

var heights = $('#elementID').siblings().map(function ()
{
   return $(this).height();
}).get();
Episcopalian answered 16/7, 2010 at 4:9 Comment(1)
I was trying $(this).siblings.each(function()... and nothing was happening. Duhhh... now that I saw your code I realized I was missing the parenthesis! siblings() This is obvious since it's a function. Lost 15 minutes debugging this. :)Wrist
T
5
$.each($('.sidebar'), function() {
    var height = $(this).height();
});
Twist answered 16/7, 2010 at 4:5 Comment(3)
thank you! learning jquery, but sometimes it is difficult to do simple things, because I do not know all events and operators.Jerilynjeritah
You're welcome. When in doubt, use the jQuery documentation: api.jquery.comTwist
What's with using jQuery.each over plain old .each()? See my answer for links to the two.Episcopalian
E
0

When I had to do the same thing, this is the code I used:

    var tabPanels = $("...");
    var maxHeight = 0;

    $.each(tabPanels, function() {
        var height = $(this).height();
        maxHeight = (height > maxHeight) ? height: maxHeight;
    });

    $.each(tabPanels, function() {
        $(this).css("height", maxHeight + "px");
    });
Efflux answered 16/7, 2010 at 4:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.