Add an element to the DOM with JavaScript

This should do what you are looking for:

    var newdiv = document.createElement("div");
    newdiv.appendChild(document.createTextNode("some text"));
    document.body.appendChild(newdiv);
<html>
    <head></head>
<body>

</body>
</html>

First, you create the element by document.createElement. To set its text contents, you have to have a “text node” wrapping your text. So, you first create such text node and then add it as (the only) child to your new object.

Then, add your newly created DIV element to the DOM structure. You don’t have to look for the BODY element with getElementsByTagName(), since it exists as a property of document object.

Leave a Comment