2014-09-25 123 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