6

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
  • 16,278
  • 7
  • 48
  • 74
user3490755
  • 955
  • 2
  • 15
  • 33
  • 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

11

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
  • 191,768
  • 25
  • 236
  • 258
4

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

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
  • 4,173
  • 1
  • 22
  • 32