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

2

3

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.

Pistil answered 16/11, 2010 at 3:23 Comment(0)
P
7
targetUl.wrap(
    $('<div />', {
        'id':'wrap',
        'css': {
            'width': maxWidth,
            'overflow':'hidden'
        }
    })
);
Pavior answered 16/11, 2010 at 3:28 Comment(2)
nice, didn't realize I could simply drop that 'creator syntax' into the .wrap function.Pistil
Since wrap clones the element, this will unnecessarily create two elements: jsfiddle.net/qBkA5Turboelectric
R
1

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

Repairer answered 16/11, 2010 at 3:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.