当前位置: 动力学知识库 > 问答 > 编程问答 >

jQuery: wrap newly created html

问题描述:

I create HTML snippet on-the-fly:

$('<span/>').addClass(spanClass)

Is there a jQuery way to wrap this code into <div>?

Semantically I want to do:

$('<span/>').addClass(spanClass).wrap($('<div/>').addClass(divClass))

that does not work. So I just want following jQuery-idiomatic version:

function wrap(what, with) { return $(with).append(what); }

网友答案:

Keep in mind that your jQuery object is still referencing the new <span>, so if you're trying to insert it with a chained method, the <div> won't be inserted.

To overcome this, you'd need to traverse up to the new parent <div> first.

    // Traverse up to the new parent in order to append the <div> and <span>
$('<span/>').addClass(spanClass).wrap($('<div/>').addClass(divClass))
            .parent().appendTo('body');

You could also write it like this:

$('<span/>').addClass(spanClass).wrap('<div/>')
            .parent().addClass(divClass).appendTo('body');
网友答案:
$('<div/>', {'class': divClass}).append($('<span/>', {'class': spanClass}));
网友答案:

Why not:

$('<div/>').addClass(divClass).append($('<span/>').addClass(spanClass));

IE create your div first?

网友答案:

Try this:

$('<span/>').addClass(spanClass).wrap($('<div/>').addClass(divClass).html()); 

or

$('<div/>').addClass(divClass).append($('<span/>').addClass(spanClass));
分享给朋友:
您可能感兴趣的文章:
随机阅读: