Reputation: 81
How do I do the following without jQuery and with pure JavaScript:
What I'm trying to do is to get the height of the image within the figure element and if the image's height is less than 200 pixels than I want its container's (parent's) height to be set to auto.
The jQuery method below is working but I want to do this with JavaScript.
see fiddle here.
HTML
<figure>
<img class="imgH" height="500" width="500" src="/some_img.jpg"/>
</figure>
<figure>
<img class="imgH" height="500" width="500" src="/some_img.jpg"/>
</figure>
<figure>
<img class="imgH" height="500" width="500" src="/some_img.jpg"/>
</figure>
<figure>
<img class="imgH" height="250" width="250" src="/some_img.jpg"/> // This image height is less than 300 pixels.
</figure>
<figure>
<img class="imgH" height="500" width="500" src="/some_img.jpg"/>
</figure>
CSS
figure {
width: 500px;
height: 500px;
}
JavaScript (jQuery)
$(document).ready(function(){
$(".imgH").each(function(){
if( $(this).height() < 200 ) {
$(this).parent().height( "auto" );
}
});
});
Upvotes: 1
Views: 951
Reputation: 77512
window.onload = function () {
[].forEach.call( document.querySelectorAll('.imgH'), function(node, i) {
if (node.clientHeight < 200) {
node.parentNode.style.height = 'auto';
}
});
}
DEmo: http://jsfiddle.net/6tjn7675/4/
Upvotes: 1
Reputation: 3523
so a little bit confusing but are you saying that the jquery version is working but you want it in normal javascript?
If so something like:
if( this.offsetHeight< 200 ) {
var container = this.parentNode;
container.style.height = "auto";
}
Is an equivalent statement.
Upvotes: 1
Reputation: 63
From what I can remember:
document.querySelector
to get all the image nodes.naturalHeight
and naturalWidth
properties will get you the computed height and width of the images.parentNode
property of the image node will get you the parent. Apply the required styles and you should be done.Edit: Just saw Dave Walker's answer. naturalWidth and naturalHeight will give you the original height and width of the image. To get the computed/displayed height and width you must use offsetHeight and offsetWidth.
Upvotes: 0
Reputation: 4686
Try something like this:
HTML
<div class="image-container">
/* image goes here */
</div>
jQuery
$('.image-container').each(function() {
if ($(this).find('img').length < 300 ) {
$(this).css({'height' 'auto'});
}
});
Upvotes: 0