有很多方法 去做這個。方法的一個顯着區別是,如果您選擇先使用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