2

Is it possible transform one DOM element to another? By jQuery or even by JavaScript.

I just to want for example: get table > thead > tr > th's with all classes, attributes, properties and put it in table > body like as tr > td.

Or maybe is another way for that?

bor
  • 181
  • 1
  • 6

2 Answers2

4

You have a couple options.

  • You can use jQuery's clone(), which will copy everything on/in the DOM node. Then use append() to attach the clone to whatever element you want it moved to. Then just remove the original node.

  • If you just want the attributes from the DOM node (classes, id, etc.) then you can use the attributes array that is present on all DOM nodes. You'd have to loop through each attribute and then set it on the new element individually though. I have yet to find a simple way to just copy everything over. In vanilla Javascript that would look something like this:

    var originalELement = document.getElementById('original-element-id');
    var newElement = document.createElement('div');
    
    for (var i = 0; i < originalElement.attributes.length; i++) {
        var attr = originalElement.attributes.item(i);
        newElement.setAttribute(attr.nodeName, attr.nodeValue);
    }
    
Chris Dolphin
  • 1,578
  • 16
  • 28
0

when you do element1.append(element2) element2 will move inside element1. append or appendChild. weird but true. append actually means "cut"