2

I have an existing HTML as;

<div id="maincontent">
        <div id="firstname_lbl"></div>
        <div id="firstname_fld"></div>
</div>

I am creating a jQuery form dynamically as ;

$('<' + items.type + '/>').attr({
        "action": items.action,
         "name": items.name,
         "class": items.attributes.class
        })

Now I want this "form" element to become the parent of the existing "maincontent" div

So the DOM should then look like;

<form>
<div id="maincontent">
            <div id="firstname_lbl"></div>
            <div id="firstname_fld"></div>
    </div>
</form>

How do I do this using jQuery?

Also I am getting Expected identifier in IE for this line (works fine in Firefox);

var formEle = $('<' + items.type + '/>').attr({
        "action": items.action,
         "name": items.name,
         "class": items.attributes.class});
copenndthagen
  • 49,230
  • 102
  • 290
  • 442

2 Answers2

4

You should use wrap:

var form = $("<" + items.type + "/>").attr({
    action: items.action,
    name: items.name,
    "class": items.attributes["class"]
});

$("#maincontent").wrap(form);
VisioN
  • 143,310
  • 32
  • 282
  • 281
  • Thx a lot...Is there some chaining possible where I create the form ? – copenndthagen Jan 30 '13 at 13:27
  • @testndtv Unfortunately there is no method like `wrapAround(smth)` in jQuery. – VisioN Jan 30 '13 at 13:28
  • @testndtv: You can use `form.append($("#maincontent"))` and then go on chaining with form. Or you can use the `wrap` from above, but without an extra `form` variable. – Bergi Jan 30 '13 at 13:34
  • @testndtv `class` is a reserved word in IE. That's why initially I've put `class` in quotes in my answer. – VisioN Jan 30 '13 at 13:39
0

A great solution is provided here: How to move child element from one parent to another using jQuery.

Here's the code:

(function($){
    $.fn.moveTo = function(selector){
        return this.each(function(){
            var cl = $(this).clone();
            $(cl).appendTo(selector);
            $(this).remove();
        });
    };
})(jQuery);

$('#maincontent').moveTo('[FormSelectorHere]');
Community
  • 1
  • 1
James Hill
  • 60,353
  • 20
  • 145
  • 161