简体   繁体   中英

Wrap a span around all children

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:

<div>
<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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM