8

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?

user2143356
  • 5,467
  • 19
  • 51
  • 95
  • 1
    possible duplicate of [Inserting HTML elements with JavaScript](http://stackoverflow.com/questions/814564/inserting-html-elements-with-javascript) – Lukas Knuth Apr 17 '13 at 22:08

4 Answers4

17

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"));
Elliot Bonneville
  • 51,872
  • 23
  • 96
  • 123
  • Great. Thanks. Any idea how to delete exactly the created element later (separate part of the script)? – user2143356 Apr 17 '13 at 15:22
  • Sure. Since we've stored a reference to the element `div` already, we can just do this: `div.parentNode.removeChild(div);` – Elliot Bonneville Apr 17 '13 at 15:28
  • You _can_ do it in a one-liner because `appendChild` _is_ chainable: `document.getElementsByTagName('body')[0].appendChild(document.createElement("div")).innerHTML = "some HTML";`. Long line though. – Andrew Willems Feb 22 '16 at 19:15
5

document.createElement rather than createTextNode

Andy
  • 14,427
  • 3
  • 52
  • 76
1

There're a lot of methods:

elem.innerHTML = ''   // fast
elem.appendChild()    
elem.insertAdjacentElement()  //fast    
elem.insertAdjacentHTML()
elem.insertAdjacentText()
Stone Shi
  • 106
  • 4
0
document.body.innerHTML+=document.createElement('div').outerHTML;
Thielicious
  • 4,122
  • 2
  • 25
  • 35