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.
精彩评论