shinra tensei
shinra tensei

Reputation: 713

getting the height of the div within another div

I have a div which i need to get the height of. It is inside a div and it has several divs inside of it. They're both inside a similar div structure. I made a js fiddle to illustrate my problem and with what i have so far. http://jsfiddle.net/K3dx5/

So basically I need to get the height of the first div when a link is clicked(400px), also on the second link(200px).

<div class="wrapper">
    <div class="one">  <!--I need to get the height of this div -->
    <div class="NotThisone">
       <div class="No">
    <a class="anchor">ONE</a>
        </div>
    </div>
</div>
<div class="two"> <!--I need to get the height of this div -->
    <div class="NotThistwo">
        <div class="No">
    <a class="anchor">TWO</a>
        </div>
    </div>    
</div>

Thank you

Upvotes: 0

Views: 63

Answers (4)

NathanC
NathanC

Reputation: 71

The issue in the fiddle is you are selecting the imediate parent, though meanwhile the div that you want is 2 more levels higher. Switching that select to this does the job.

var x = $(this).parent().parent().parent().css('height');

This looks a little messy and unreliable (if you change your html to add more divs around the anchor tag, the javascript will select the wrong div again) so if you add a common class to the divs that you want the height to you can then select the specific parent. So lets say i added the class called "parentNeeded" to the divs "one" and "two", you can then use the following statement

var x = $(this).parents(".parentNeeded").css('height');

You can see this in this fiddle http://jsfiddle.net/K3dx5/5/

Upvotes: 0

AGB
AGB

Reputation: 2448

Your selector is wrong.

var x = $(this).parent().parent().parent().css('height');

The div in question is three levels up from the anchor so you need to use three parent() methods.

Or you could use a different selector.

Upvotes: 0

David Thomas
David Thomas

Reputation: 253308

I'd suggest using closest() method, with a selector:

$('.anchor').click(function() {
    var height = $(this).closest('.wrapper > div[class]').height();
    console.log(height);
});​

Updated JS Fiddle demo.

References:

  • closest().

Upvotes: 1

xdazz
xdazz

Reputation: 160833

For the first , use

var x = $(this).closest('.one').height();

For the second, use

var x = $(this).closest('.two').height();

Upvotes: 0

Related Questions