1

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 6

4

Try using wrapInner function like below,

$('#test').wrapInner('<span/>');
Sign up to request clarification or add additional context in comments.

Comments

1

You're looking for the wrapInner() method.

Comments

1

use $.wrapInner like this

$('#test').wrapInner('<span/>');

Comments

1

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

1

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

0

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.