2014-09-25 85 views
1

即時通訊目前使用下面的代碼追加一個div機體:如何將元素追加到正文?

$("body").append('<div class="tooltip" id="op" style="position: absolute; z-index: 999; height: 16px; width: 16px; top:70px"><span>Test</span></div>'); 

我怎麼能這樣做上述相同,但沒有使用jQuery

+0

的[添加div元素到在javascript體或文件(可能重複http://stackoverflow.com/questions/15741006/adding-div-元素到正文或文檔在JavaScript中) – Huangism 2014-09-25 16:20:46

回答

3

在純JavaScript這將是多一點點冗長:

var div = document.createElement('div'); 
 
div.className = 'tooltip'; 
 
div.id = 'op'; 
 
div.style.cssText = 'position: absolute; z-index: 999; height: 16px; width: 16px; top:70px'; 
 
div.innerHTML = '<span>Test</span>'; 
 

 
document.body.appendChild(div);

1

我真的很喜歡insertAdjacentHTML方法爲所有現代瀏覽器 - 並且還支持舊版瀏覽器。

參考:http://updates.html5rocks.com/2011/08/insertAdjacentHTML-Everywhere

用法:

var html = '<div class="tooltip" id="op" style="position: absolute; z-index: 999; height: 16px; width: 16px; top:70px"><span>Test</span></div>'; 
document.body.insertAdjacentHTML('beforeend', html); 
+1

Tada !! 'insertAdjacentHTML'可能是最被低估和非常少見的方法之一!現在這就是答案! – dfsq 2014-09-25 16:25:19