Kiee
Kiee

Reputation: 10771

jquery get height of div

I have 3 divs.

<div class="bg1"></div>
<div class="bg2"></div>
<div class="bg3"></div>

And I'm trying to get the heights of them and set their css with jquery.

$('[class^=bg]').each(function(key,val){
     // tried, val.height() val.outerHeight val.innerHeight, this.height() etc
});

console.log(val) just shows <div class="bg1"></div> instead of a jquery object, how would I go about getting and changing the height of each div in this loop?

Upvotes: 0

Views: 93

Answers (2)

Neablis
Neablis

Reputation: 914

I would suggest changing your code a little bit by adding a new class.

<div class="bg bg1"></div>
<div class="bg bg2"></div>
<div class="bg bg3"></div>

then you can proceed to not use jquery easier.

var dom = document.getElementsByClassName('bg'), height = '50';

for( var x = 0; x < dom.length; x++ ){
    dom[0].style.height = height;
}

Upvotes: 1

VinceFior
VinceFior

Reputation: 1279

You're correct that your functions don't work because val is a DOM object instead of a jQuery object. You can get the effect you want by converting each val DOM object into a jQuery object by wrapping it with $().

This code should work the way you want:

$('[class^=bg]').each(function(key,val){
    $(val).height();
    // or $(val).height(100) etc.
});

Upvotes: 1

Related Questions