Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add to DOM without jQuery

Tags:

javascript

This should be simple, but it's not.

document.getElementsByTagName('body')[0].document.createTextNode( document.createElement('<div>some HTML</div>') );

It creates as a text node. How do I do it so I simply add HTML without jQuery?

like image 555
user2143356 Avatar asked Apr 17 '13 15:04

user2143356


3 Answers

Close, but no cigar. You have to create the element manually (via createElement), and then append it, like this:

var div = document.createElement("div");
div.innerHTML = "some HTML";
document.getElementsByTagName('body')[0].appendChild(div);

Unfortunately, you can't do this in a one-liner because there's no function to set the innerHTML property of an element, which means it isn't chainable. With a bit of preparation you can make this possible, though:

function setInnerHTML(element, content) {
    element.innerHTML = content;
    return element;
} 

document.getElementsByTagName('body')[0].appendChild(setInnerHTML(document.createElement("div"), "some HTML"));
like image 135
Elliot Bonneville Avatar answered Sep 24 '22 06:09

Elliot Bonneville


document.createElement rather than createTextNode

like image 25
Andy Avatar answered Sep 23 '22 06:09

Andy


There're a lot of methods:

elem.innerHTML = ''   // fast
elem.appendChild()    
elem.insertAdjacentElement()  //fast    
elem.insertAdjacentHTML()
elem.insertAdjacentText()
like image 44
Stone Shi Avatar answered Sep 22 '22 06:09

Stone Shi