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>
The parent() method returns the direct parent element of the selected element. The DOM tree: This method only traverse a single level up the DOM tree. To traverse all the way up to the document's root element (to return grandparents or other ancestors), use the parents() or the parentsUntil() method.
The parents() is an inbuilt method in jQuery which is used to find all the parent elements related to the selected element. This parents() method in jQuery traverse all the levels up the selected element and return that all elements.
The ("parent > child") selector selects all elements that are a direct child of the specified element.
The :parent Selector page on jQuery says: Select all elements that have at least one child node (either an element or text). So $('div') would select all divs and $('div:parent') would select only those with children.
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!)
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' }
}));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With