I am trying to loop through over each div that has a class of block and set it's height individually based on it's data-attribute data-height
HTML
<div class="block" data-height="300"></div>
<div class="block" data-height="500"></div>
<div class="block" data-height="700"></div>
jQuery
$('.block').each(function(){
var size = $this.attr('data-height');
$(this).height(size);
});
JS Fiddle /
It's not returning the height when I have it in the each method though thus not setting the height for each one.
I am trying to loop through over each div that has a class of block and set it's height individually based on it's data-attribute data-height
HTML
<div class="block" data-height="300"></div>
<div class="block" data-height="500"></div>
<div class="block" data-height="700"></div>
jQuery
$('.block').each(function(){
var size = $this.attr('data-height');
$(this).height(size);
});
JS Fiddle http://jsfiddle/MLnBY/166/
It's not returning the height when I have it in the each method though thus not setting the height for each one.
Share Improve this question asked Mar 28, 2015 at 14:34 MyojiMyoji 2794 silver badges13 bronze badges 4-
1
data-*
attributes can be also accessed by doing.data('height');
. – D4V1D Commented Mar 28, 2015 at 14:37 - @D4V the way OP is doing it is still valid. – nicael Commented Mar 28, 2015 at 14:37
- 1 I know, I never said it was invalid. Just pointing that out :) – D4V1D Commented Mar 28, 2015 at 14:38
- $(this).data("height") – Smile0ff Commented Mar 28, 2015 at 14:43
3 Answers
Reset to default 5The problem is in $this
; replace it with $(this)
var size = $(this).attr('data-height');
You forgot the () on the second line of JS at $(this)
Hey you can do it using pure javascript like this:
var size = this.getAttribute('data-height');