-1

so I was trying to dynamically create an element in Jquery, and then wrap that in a more simplistic element using jquery wrap. I tried the following, and it did not work:

jQuery('<div />',{
       "class":"b",
       text:"testing"
       }).wrap('<div class="red" />');

jsfiddle

then after a search, I cam across this question, which seemed to be what I was looking for.

Unfortunately that code is for placing inside the created element rather than wrapping the created one. I tried messing around with it, but as of now it seems to me that there is no way to simply wrap a Jquery created element.

Is this a bug in the function? Or am I missing something?

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Ryan Saxe
  • 17,123
  • 23
  • 80
  • 128

2 Answers2

2

This snippet:

jQuery('<div />',{
       "class":"b",
       text:"testing"
       }).wrap('<div class="red" />');

returns a reference to the first object, the div you created, not the one you wrapped it in. Here's an alternative that works:

http://jsfiddle.net/vVxzc/

var test = jQuery('<div />',{
       "class":"b",
       text:"testing"
       }).wrap('<div class="red" />').parent();
$('#append2').append(test);
Jason P
  • 26,984
  • 3
  • 31
  • 45
2

You're appending the item that was wrapped to another element, this will cause it to be removed from wherever it was i.e. wrapped inside red div. What you have to do is append the red div to the element. wrap gives you back the original elements not the wraping element.

var test = jQuery('<div />',{
       "class":"b",
       text:"testing"
       }).wrap('<div class="red" />').parent();
$('#append2').append(test);

http://jsfiddle.net/mowglisanu/ySbg7/1/

Musa
  • 96,336
  • 17
  • 118
  • 137