4

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?

Huangism
  • 15,899
  • 5
  • 47
  • 67
user3490755
  • 915
  • 2
  • 15
  • 31
  • possible duplicate of [Adding div element to body or document in javascript](http://stackoverflow.com/questions/15741006/adding-div-element-to-body-or-document-in-javascript) – Huangism Sep 25 '14 at 16:20

4 Answers4

6

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);
dfsq
  • 187,712
  • 24
  • 229
  • 250
2

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);
  • 1
    Tada!! `insertAdjacentHTML` is probably one of the most underestimated and very less known methods! Now this is the answer! – dfsq Sep 25 '14 at 16:25
-1

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

-1

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

Vibhor Dube
  • 2,514
  • 1
  • 19
  • 25