user2143356
user2143356

Reputation: 5607

Add to DOM without jQuery

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?

Upvotes: 8

Views: 13245

Answers (4)

Thielicious
Thielicious

Reputation: 4452

document.body.innerHTML+=document.createElement('div').outerHTML;

Upvotes: 0

Elliot Bonneville
Elliot Bonneville

Reputation: 53351

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

Upvotes: 17

Stone Shi
Stone Shi

Reputation: 106

There're a lot of methods:

elem.innerHTML = ''   // fast
elem.appendChild()    
elem.insertAdjacentElement()  //fast    
elem.insertAdjacentHTML()
elem.insertAdjacentText()

Upvotes: 1

Andy
Andy

Reputation: 14575

document.createElement rather than createTextNode

Upvotes: 5

Related Questions