Reputation: 6127
I am new to jQuery and i have a problem.
I have script that for resize each image in some div. And i want to insert that image into non existing div (create div-parent), how?
EDIT:
I've got this code:
$('#content img').each(function() {
if( $(this).width() > maxWidth || $(this).height() > maxHeight )
{
var ratio = 0;
if( $(this).width() > $(this).height() )
{
ratio = maxWidth / $(this).width();
$(this).css('width', maxWidth + 'px');
$(this).css('height', ( $(this).height() * ratio) + 'px' );
}
else
{
ratio = maxHeight / $(this).height();
$(this).css('width', ($(this).width() * ratio) + 'px');
$(this).css('height', maxHeight + 'px');
}
$(this).addClass('scaled-img');
$(this).wrap('<div class="test"></div>'); // trying to add
}
});
});
Result:
<img src="path.."/>
Result that i want:
<div><img src="path"/></div>
Upvotes: 8
Views: 25088
Reputation: 614
I can't for the life of me figure out why these solutions are not working for me:
//everything is an array of 14 items
//footer is in my html andi've tested manually adding the <div class="dot></div> and it works
everything.forEach(function(){
d = document.createElement('div');
//this console log proves that it is being created 14 times
console.log(d)
$(d).addClass("dot").appendTo($('.footer'))
//or this: $('.footer').append(d);
})
Upvotes: 0
Reputation: 359826
Use .wrap()
.
<div id="some-div">
<img ... />
<img ... />
<img ... />
</div>
$(function ()
{
$('#some-div > img').wrap('<div class="new-parent"></div>');
});
<div id="some-div">
<div class="new-parent"><img ... /></div>
<div class="new-parent"><img ... /></div>
<div class="new-parent"><img ... /></div>
</div>
Demo (now with extra kittens!)
Upvotes: 31
Reputation: 12368
$('#demowrap').wrap('<div id="parent"></div>');
where demowrap is the id on the img (u can change this to whatever selects your image. http://api.jquery.com/wrap/
Upvotes: 1
Reputation: 253318
Without the specifics of your script, and marm-up, it's difficult to answer this question properly. But, for general information: to add an image to a div, you can use either prependTo()
or appendTo()
.
$('img').appendTo('#elementToAddImageTo');
You could also use:
$('#elementToAddImageTo').append($('img'));
If you simply want to wrap the img
elements with a div
then use wrap()
:
$('img').wrap('<div></div>');
Upvotes: 1
Reputation: 413717
Look at the ".wrap()" jQuery method. It lets you wrap en element in some other container element:
$('#myImage').wrap('<div></div>');
If you need to give the container some properties:
$('#myImage').wrap($('<div></div>', {
id: "newWrapper",
class: 'wrapper banana',
css: { 'borderColor': 'green', 'borderWidth': '2px' }
}));
Upvotes: 5