javascript 使用javascript在另一个div之后附加一个div

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16936451/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 06:31:44  来源:igfitidea点击:

Append a div after another div with javascript

javascript

提问by Anjil panchal

Is there any predefined method in javascript that can append div after a div? For example:

javascript 中是否有任何预定义的方法可以在 div 后附加 div?例如:

<div class="uploader">
    <div class="file-metas">
        <div class="file-name">status<span class="file-size">1kb</span></div>
        <p class="state state-success">Success</p>
    </div>
</div>

Now I want to insert another div with class name 'remove' after 'uploader' div.

现在我想在 'uploader' div 之后插入另一个类名为 'remove' 的 div。

回答by K D

Yeah it is possible using pure javascript

是的,可以使用纯 javascript

You can use insertBefore method to do so by accessing parent node of target element.

您可以使用 insertBefore 方法通过访问目标元素的父节点来执行此操作。

document.getElementsByClassName("uploader").parentNode

Take a look

看一看

回答by Givi

Try this Demo

试试这个演示

var node = document.querySelector(".uploader"),
    ele = document.createElement("div");

ele.className = "remove";
ele.innerHTML = "some text";
node.parentNode.insertBefore(ele, node.nextSibling);

回答by Software Guy

The following example demonstrates what you are trying to achieve using plain JavaScript:

以下示例演示了您尝试使用纯 JavaScript 实现的目标:

<html>
<head>

<script>

function addNewDiv() {
    var newDiv = document.createElement('div');
    var label = document.createTextNode(" - new div - ");
    var elements = document.getElementsByClassName('uploader');
    var uploaderDiv = elements[0];

    newDiv.appendChild(label);
    elements[0].insertBefore(newDiv, uploaderDiv.children[0]);
}    

</script>

</head>
<body>

<div class="uploader">
    <div class="file-metas">
        <div class="file-name">status<span class="file-size">1kb</span>
        </div>
        <p class="state state-success">Success</p>
    </div>
</div>

<input type="button" onClick="addNewDiv()" value="Add new Div" />

</body>
</html>

回答by sjkm

function appendAfter(divToAppend, siblingBefore) {
    if(siblingBefore.nextSibling) {
        siblingBefore.parentNode.insertBefore(divToAppend, siblingBefore.nextSibling);
    } else {
        siblingBefore.parentNode.appendChild(divToAppend);
    }
}