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?
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"));
document.createElement rather than createTextNode
There're a lot of methods:
elem.innerHTML = '' // fast
elem.appendChild()
elem.insertAdjacentElement() //fast
elem.insertAdjacentHTML()
elem.insertAdjacentText()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With