开发者

Wrap a span around all children

开发者 https://www.devze.com 2023-04-07 02:19 出处:网络
I am trying to get the contents of a div and wrap a span around it and append back to the div. From this:

I am trying to get the contents of a div and wrap a span around it and append back to the div.

From this:

<div>
<a href="#">12</a>
Testing
</div>

To this:

<d开发者_Go百科iv>
<span>
<a href="#">Hehhehe</a>
Testing
</span>
</div>

So I tried this:

var span = $(document.createElement('span'));

var contents = window.jQuery(this).children();

span.append(contents);

window.jQuery(this).append(span); // I am looping here but this is the div

However, the text "Testing" is always outside the span!

How can I get everything to be within the span?


This should do what you want..

$('div').wrapInner('<span>');

Demo at http://jsfiddle.net/gaby/76ND5/


If in your code this refers to the div in question, then all you need is

$(this).wrapInner('<span>');


.children() doesn't include text nodes. Use .wrapInner to add the span around your elements.

0

精彩评论

暂无评论...
验证码 换一张
取 消