最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to append element to body? - Stack Overflow

programmeradmin2浏览0评论

Im currently using the following code to append a div to the body:

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

How could I do the same as above but without the use of jQuery?

Im currently using the following code to append a div to the body:

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

How could I do the same as above but without the use of jQuery?

Share Improve this question edited Sep 25, 2014 at 16:19 Huangism 16.4k7 gold badges50 silver badges75 bronze badges asked Sep 25, 2014 at 16:12 user3490755user3490755 9953 gold badges15 silver badges34 bronze badges 1
  • possible duplicate of Adding div element to body or document in javascript – Huangism Commented Sep 25, 2014 at 16:20
Add a comment  | 

4 Answers 4

Reset to default 13

In pure Javascript it's going to be a little bit more verbose:

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);

I really like the insertAdjacentHTML method for all modern browsers -- and there is support for older browsers as well.

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

Usage:

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);

You can do a lot with DOM! You can manipulate simple html this way!

Check out the W3 website : http://www.w3schools.com/js/js_htmldom.asp

A simpler way would be

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

Read about insertAdjacentElement here - https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentElement

发布评论

评论列表(0)

  1. 暂无评论