将div标签添加到另一个div标签下方
我有一个div
标签,其中有类divstudent
,可以说这是div1
标签。现在我想在div1
标签以下动态创建另一个div标签div2
,而不是在div1
标签内。我想使用javascript在div1
标签之外创建。我怎样才能做到这一点?将div标签添加到另一个div标签下方
"div1"
<div class="divstudent"></div>
<!-- i want to be like this -->
<!-- "div1" -->
<div></div>
<!-- "div2" -->
<div></div>
<!-- "div3" -->
<div></div>
尝试这样:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Divs creator</title>
<script type="text/javascript">
window.onload = function() {
var divReference = document.querySelector('.divstudent');
var divCounter = 0;
divReference.addEventListener('click', function() {
var divToCreate = document.createElement('div');
divToCreate.innerHTML = ++divCounter;
divReference.parentNode.appendChild(divToCreate);
}, false);
}
</script>
</head>
<body>
<div class="divstudent">
<input type="button" value="add div below divstudent">
</div>
</body>
</html>
您创建一个新的div(在js中),然后在目标div之后添加您的newDiv。沿线的香草JS的东西:
// Create your new div
var newDiv = document.createElement("div");
newDiv.innerText = "New Div!";
// Grab the div you want to insert your new div after
var target_div = document.querySelector("div.divstudent");
// Insert newDiv after target_div (before the thing after it)
target_div.parentNode.insertBefore(newDiv, target_div.nextSibling);
有很多方法 去做这个。方法的一个显着区别是,如果您选择先使用Document.createElement()
创建元素,然后插入元素,或者使用允许插入HTML文本的方法之一在一个步骤中创建和插入元素。
因为它更简单但不一定更好,下面的示例显示了使用允许将HTML文本插入到DOM中的方法在一个步骤中创建和插入两个<div>
元素。
的JavaScript:
一种是使用insertAdjacentHTML()
并指定它要插入您所使用的元素afterend
。
document.querySelector()
用于查找第一个<div class="divstudent">
。然后使用insertAdjacentHTML()
添加附加的<div>
元素。然后使用Element.removeAttribute()
删除class="divstudent"
。注意:如果我们只是想将class
设置为不同的值,即使''
,那么我们也可以使用Element.className
。
注:在这个答案,文字识别每个<div>
已被添加到<div>
太有东西在这个答案的例子可见。
//Find the first <div class="divstudent"> in the document
var studentDiv = document.querySelector('div.divstudent');
//Insert two new <div> elements.
studentDiv.insertAdjacentHTML('afterend','<div>2</div><div>3</div>');
//Remove the class="divstudent"
studentDiv.removeAttribute('class');
<div class="divstudent">1</div>
的jQuery:
虽然你的问题是标签的jQuery,您发布的评论你只是使用JavaScript暗示。因此,我不确定jQuery是否适合你。
如果您想使用jQuery,那么您可以使用.after()
来添加<div>
元素。然后您可以使用.removeAttr()
删除class="divstudent"
。
// Get the first <div class="divstudent">.
// Store it in a variable so we only walk the DOM once.
var $studentDiv = $('div.divstudent').eq(0);
//Add the two new <div> elements
$studentDiv.after('<div>2</div><div>3</div>');
//Remove the class="divstudent"
$studentDiv.removeAttr('class');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="divstudent">1</div>
只是一个侧面说明,HTML注释表示'' –
几乎同样的问题: http://*.com/questions/ 4793604 /如何在JavaScript中不使用插入后使用库 –
你有什么尝试?顺便说一句:如果你给它一个唯一的'id',除了'class'之外,引用一个特定的元素会容易得多。 – Makyen