Aleksandra
Aleksandra

Reputation: 21

How to get height of the clossest div element

I have multiple div elements with multiple heights. For each table I need to get height of the closest div element that the table is inand assign it to it. I used clossest() and parents() but it doesn't work as it always gets a height of the last div element that is on the page and assigns it to all tables. And what i need is the height of the table should be the same as the div that the table is in.

<div>Some Text here</div>
<div>
<table id="firstTable">
    <tr> <th>Header 1</th>
        <th>Header 2</th>
        <th>Headier 3</th>
    </tr>
    <tr>
        <td>info</td>
        <td>info</td>
        <td>info</td>
    </tr>
</table>
</div>  

</div>

<div class="dragitem" style="height: 300px">
<div>Some Text here</div>
<div>
  <table id="secondTable">
    <tr> <th>Header 1</th>
        <th>Header 2</th>
        <th>Headier 3</th>
    </tr>
    <tr>
        <td>info</td>
        <td>info</td>
        <td>info</td>
    </tr>
</table>
   </div>   

</div>

i have tried:

$('#firstTable').closest('div.dragitem').height();
$('#firstTable').parents('div.dragitem').height();

but none of this works. It always get the height of the last div with class name dragitem and assigns it to all tables. So in this example firstTable would have height 300px. What i need is for the first table to be 600px and second table to be 200px. Thank you for any help

Upvotes: 0

Views: 85

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

Part of the problem is because you've used the same id attribute multiple times. id must be unique within the page. Instead you can use a class to group common elements.

From there you can loop through each .firstTable element and use closest() to get the height of its parent .dragitem div, like this:

$('.firstTable').each(function() {
    console.log($(this).closest('div.dragitem').height());
});

Working example

Upvotes: 2

Related Questions