在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>
现在我想在'uploader'div。
之后插入另一个名为'remove'的div答案 0 :(得分:3)
是的,可以使用纯javascript
您可以通过访问target element的父节点来使用insertBefore方法。
document.getElementsByClassName("uploader").parentNode
<强> Take a look 强>
答案 1 :(得分:3)
试试这个Demo
var node = document.querySelector(".uploader"),
ele = document.createElement("div");
ele.className = "remove";
ele.innerHTML = "some text";
node.parentNode.insertBefore(ele, node.nextSibling);
答案 2 :(得分:0)
function appendAfter(divToAppend, siblingBefore) {
if(siblingBefore.nextSibling) {
siblingBefore.parentNode.insertBefore(divToAppend, siblingBefore.nextSibling);
} else {
siblingBefore.parentNode.appendChild(divToAppend);
}
}
答案 3 :(得分:0)
以下示例演示了您尝试使用纯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>
答案 4 :(得分:0)
Vanilla JS:支持所有浏览器:
职位名称的可视化
<!-- beforebegin -->
<p>
<!-- afterbegin -->
foo
<!-- beforeend -->
</p>
<!-- afterend -->
代码
// <div id="one">one</div>
var d1 = document.getElementById('one');
d1.insertAdjacentHTML('afterend', '<div id="two">two</div>');
// At this point, the new structure is:
// <div id="one">one</div><div id="two">two</div>
更多信息here