jQuery: How to create element then wrap this around another existing element?

我的梦境 提交于 2019-12-20 02:56:51

问题


So I know how to use .wrap, .wrapInner and .wrapAll but I am wondering how to use the quick creation syntax introduced in jQuery 1.4 and the wrap function together.

Basically I want to be able to use

var targetUl = $(this), // would be populated by script
    maxWidth = 1400;    // would be populated by script

$('<div />', {
    'id':'wrap',
    'css': {
        'width': maxWidth,
        'overflow':'hidden'
    }
}).wrapAround(targetUl);

Kinda like the .appendTo method works but for wrapping stuff…

Can this be done?

Thanks.


回答1:


targetUl.wrap(
    $('<div />', {
        'id':'wrap',
        'css': {
            'width': maxWidth,
            'overflow':'hidden'
        }
    })
);



回答2:


jQuery .wrap() is what you're looking for. It provides this functionality in a neater way



来源:https://stackoverflow.com/questions/4190946/jquery-how-to-create-element-then-wrap-this-around-another-existing-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!