So my dom generates divs <div id="test">random text goes here</div> is it possible to jquery insert a span tag inside of this div like: <div id="test"><span>random text goes here</span></div>
6 Answers
Or if you want total control over your inner stuff (like you also want to make some modifications in your method) you can use it this way:
$("div#test").append(function () {
//you can refer to the object you are making modifications in as 'this'
var txt = $(this).text();
//do your modifications for the 'txt' if needed
//..
//finally use return statement to return the value or
//object you need to the original append function
//$("<span>") creates a span html element
return $("<span>").text(txt);
});
This question has been answered by many guy with wrapInner() method, I just wanted to show you how you how you can make some 'magic" inside the function
Comments
Absolutely, check out $.wrapInner():
Wrapping Element
/* Wrap an HTML structure around the content of each matched element */
$("#test").wrapInner("<span>");
Callback Function
Alternatively, you can use a anonymous function to gain a bit more control:
$("#test").wrapInner(function() {
return '<span class="' + this.id + '" />';
});
Which would apply the id values as a class name:
<div id="test">
<span class="test">random text goes here</span>
</div>
Comments
As answered by others you can use wrapInner. Otherwise you can do it just by using html method
$('#test').html($('<span>').html($('#test').html()));
fiddle : http://jsfiddle.net/zcg9B/