简体   繁体   English

将元素设为父元素

[英]Make element as parent element

I have an existing HTML as; 我有一个现有的HTML作为;

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

I am creating a jQuery form dynamically as ; 我正在动态创建jQuery表单;

$('<' + 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 现在,我希望此“ form”元素成为现有“ maincontent” div的父级

So the DOM should then look like; 因此,DOM应该看起来像;

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

How do I do this using jQuery? 我该如何使用jQuery?

Also I am getting Expected identifier in IE for this line (works fine in Firefox); 我也正在IE中获得此行的Expected标识符(在Firefox中可以正常工作);

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

You should use wrap : 您应该使用wrap

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

$("#maincontent").wrap(form);

A great solution is provided here: How to move child element from one parent to another using jQuery . 这里提供了一个很好的解决方案: 如何使用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]');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM