Reputation: 995
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
?
Upvotes: 8
Views: 12844
Reputation: 5053
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
Upvotes: -1
Reputation: 311
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);
Upvotes: 5
Reputation: 193261
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);
Upvotes: 13
Reputation: 19
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
Upvotes: -1