Jquery - adding parent

Jquery - adding parent

回答1

Use .wrap().

HTML

<div id="some-div">
    <img ... />
    <img ... />
    <img ... />
</div>

JavaScript

$(function ()
{
    $('#some-div > img').wrap('<div class="new-parent"></div>');
});

Result

<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!)

 

回答2

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' }
}));

 

回答3

$('#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/

 

 

posted @ 2022-03-02 14:05  ChuckLu  阅读(36)  评论(0)    收藏  举报