Reputation: 5607
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
Reputation: 4452
document.body.innerHTML+=document.createElement('div').outerHTML;
Upvotes: 0
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
Reputation: 106
There're a lot of methods:
elem.innerHTML = '' // fast
elem.appendChild()
elem.insertAdjacentElement() //fast
elem.insertAdjacentHTML()
elem.insertAdjacentText()
Upvotes: 1