简体   繁体   中英

.appendChild() an HTML element on click

I wanted to copy an entire row including its' siblings and contents on button click. When I click the button the element, it appears in the console but doesn't append to the page. This is my code:

It doesn't show any error messages. I've tried innerHTML/outerHTML or append() it doesn't work.

$(document).ready(function() {

    $('#addSubFBtn').on('click', function() {
        var itm = document.getElementById("trFb");
        var wrapper = document.createElement('div');
        var el = wrapper.appendChild(itm);
        document.getElementById("tbFb").append(el);
        console.log(el);
    });
});

Seems like what you're trying to do is clone the item after you get it from your document. W3schools website explains how to accomplish this. Check out the link: https://www.w3schools.com/jsref/met_node_clonenode.asp

Once you clone the node, [appendchild] should work as intended

Not sure (as said without seeing related HTML) but i see flaw in your logic:

var itm = document.getElementById("trFb"); still exist on the document(so in the page) so you've to retrieve it before you want to add/move it to another place. using .removeElement will return you removed element(or null if no element matche the selector) so correct script should be:

var itm=document.getElementById("trFb").parentNode.removeChild(document.getElementById("trFb")); as shown here to remove element you've to use method on to parent element. So you can add it to any other element existing. For more specific use or element created in global JS variable (such an createElement not yet appended) you can see : document.createDocumentFragment(); as explained here https://developer.mozilla.org/en-US/docs/Web/API/Document/createDocumentFragment

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