o_O
o_O

Reputation: 5737

How to append an element, all its children, and all classes of the parent and children with jQuery

I have a function that is successful in removing an element and appending it elsewhere on the page as successful. The problem is that as soon as the document is ready jQuery adds classes and attributes to the children that upon moving are lost. I need these classes and attributes to remain after removing and appending. I have thought about calling the original function that adds the classes, but the problem is they are key based and rely on their position prior to the move, calling it after changes the key and thus will add brand new and different classes.

The classes adding jQuery is pretty standard:

$(function(){
    $("div").each(function(key){
        if ($(this).hasClass("container")){
            $(this).find("ul").addClass("parent" + key);
            $(this).find(".container-item").attr("parentClass", ".parent" + key);
        };
    });
});

The remove/append function:

function copy_item(draggable, target){
    var account = clone_items(draggable);
    //$('#'+name.uid).remove();
    $('#'+name.uid).hide();
    target.append(make_div(name, true, true));
    //$(draggable).children().attr("class", ($(draggable).children().attr("class")));
}
function make_div(name, drag, drop){
    var newdiv = document.createElement('div');
    newdiv.setAttribute('id', name.uid);
    newdiv.appendChild(make_h3(name.username));
    ul = document.createElement('ul');
    ul.setAttribute("class", "domain_list");
    newdiv.appendChild(ul);
    for (j = 0; j < name.domains.length; ++j) { 
        ul.appendChild(make_li(name.domains[j], drag));
    }
    return newdiv;
}

The end result in the HTMl is basically:

<div class="container">
    <ul class="parent0">
        <li parentClass="parent0">
        <li parentClass="parent0">

When recreating this structure, I need to have the class "parent0" and the parentClass attribute intact. Above you can see I've tried hiding the element, ensuring that it still stays a valid element with the correct classes/attributes, but in the end that still didn't work out. Ideally, I could remove the element entirely and recreate it with the correct classes.

Upvotes: 1

Views: 179

Answers (1)

jjenzz
jjenzz

Reputation: 1559

If I am correct in my understanding of what you are trying to do, you do not need to .remove() and recreate the element in order to move it. You can just do this:

function copy_item(draggable, target) {
    // not sure what this variable is for 
    // as you don't seem to be using it?
    var account = clone_items(draggable);

    // ...however, appending an existing 
    // element to another will 'move' it
    // and preserve all of it's properties
    target.append($('#' + name.uid));
}

Upvotes: 1

Related Questions