Reputation: 3444
I am inserting a div in jquery into an image wrapper, based upon a condition (this has no importance), I have this working the way it should, but the problem is that I want to give this div a width and a height depending on the image that is its previous sibling. Not sure if it is possible to add a width and height like I am doing to a div created in jquery.
<div class="imageWrap imageWrap2">
<img src="images/image1" class="image" />
</div>
with the code the markup looks as follow:
<div class="imageWrap imageWrap2">
<img src="images/image1" class="image" />
<div class="extraDiv"></div><-- <-- added with jquery -->
</div>
jquery I have added (again the condition is of no importance nor is the placing after, append insert, etc)
$('.image').each(function(){
if ($(this).closest('.imageWrap').hasClass('imageWrap'){
$(this).after('<div class="extraDiv"></div>');
var imageWidth = $(this).prev().width();
var imageHeight = $(this).prev().height();
$('.extraDiv').width(imageWidth).height(imageHeight);
}
});
Can someone please tell me how I can get the width of each of the images and apply it to the extraDiv.
Thank you very much.
Upvotes: 0
Views: 771
Reputation: 1425
try this? (sort of hard to know whether it will work without a fiddle or plunkr):
$('.image').each(function(){
var imageWidth = $(this).width();
var imageHeight = $(this).height();
$(this).closest('.imageWrap').append('<div class="extraDiv"></div>');
$(this).siblings('.extraDiv').width(imageWidth);
$(this).siblings('.extraDiv').height(imageHeight);
});
OR:
$('.image').each(function(){
var imageWidth = $(this).width();
var imageHeight = $(this).height();
$(this).closest('.imageWrap').append('<div class="extraDiv" style="width:' + imageWidth + 'px;height:' + imageHeight + 'px;"></div>');
});
So first off you don't really need the if statement there, since by applying the closest(className)
function you're already checking whether or not it has that class name. Also you're gonna run into trouble with that last statement inside the if
since $('.extraDiv')
is going to update all of the classes with extraDiv
as its class, which i don't think is what you want to do here.
Upvotes: 1