简体   繁体   中英

Why does this insertBefore not create a dom element before and after the target div

I'm trying to write a new dom element before and after the target div. This code only works for one or the other but not both.

function addElement () {

    var newDiv = document.createElement("div");
    var newContent = document.createTextNode("This is a new text node.");
    newDiv.appendChild(newContent);

    var currentDiv = document.querySelector("#results");

    document.body.insertBefore(newDiv, currentDiv);
    document.body.insertBefore(newDiv, currentDiv.nextSibling);
}

addElement();

You can't insert the same element in two places.

If you want to insert two elements, you need to create two elements.

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