简体   繁体   中英

How to move an element from one place to another in the DOM using plain JavaScript?

I know how to do it in jQUery (untested but should work):

$('#foo').html().appendTo('#bar');
$('#foo').remove();

But how to do this in plain JS?

field = document.getElementById('e');
document.getElementById('x').innerHTML = field.parentNode.innerHTML;
field.parentNode.removeChild(field);

this is ONE solution, you can search for clonenode too.

Your jQuery code can be done like this in plain javascript:

var foo = document.getElementById("foo"),
    bar = document.getElementById("bar");
bar.innerHTML = foo.innerHTML;
foo.parentNode.removeChild(foo);

But this just copies the html code inside foo to bar as a string, then removes foo from the DOM.

Moving the nodes is also possible, like this:

var foo = document.getElementById("foo"),
    bar = document.getElementById("bar");
bar.innerHTML = "";
for (var node in foo.childNodes) {
    bar.appendChild(node);
}
foo.parentNode.removeChild(foo);

This will move the actual child nodes of foo to bar , and then remove the now empty foo .

Creating an element

   <div id="div1">
     <p id="p1">This is a paragraph.</p>
     <p id="p2">This is another paragraph.</p>
    </div>

    <script>
    var para=document.createElement("p");
     var node=document.createTextNode("This is new.");
    para.appendChild(node);

     var element=document.getElementById("div1");
    element.appendChild(para);
    </script>

Removing an element ( you must know the parent)

    <div id="div1">
     <p id="p1">This is a paragraph.</p>
     <p id="p2">This is another paragraph.</p>
    </div>
    <script>
     var parent=document.getElementById("div1");
      var child=document.getElementById("p1");
      parent.removeChild(child);
    </script>

Brought to you by http://www.w3schools.com/js/js_htmldom_elements.asp

At its simplest, there's this possibility:

var foo = document.getElementById('foo');
document.getElementById('bar').innerHTML = foo.innerHTML;
foo.parentNode.removeChild(foo);

JS Fiddle demo .

And, using a function to minimise repetition:

function moveTo(source,target){
    if (!source || !target) {
        return false;
    }
    else {
        var children = source.childNodes;
        while (children.length){
            target.appendChild(children[0]);
        }
        source.parentNode.removeChild(source);
    }
}

var bar = document.getElementById('bar'),
    foo = document.getElementById('foo');

moveTo(foo, bar);

JS Fiddle demo .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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