有很多方法 去做这个。方法的一个显着区别是,如果您选择先使用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://stackoverflow.com/questions/ 4793604 /如何在JavaScript中不使用插入后使用库 –
你有什么尝试?顺便说一句:如果你给它一个唯一的'id',除了'class'之外,引用一个特定的元素会容易得多。 – Makyen