1let myElm = document.createElement("p"); // Create a new element
2
3myElm.innerText = 'test'; // Change the text of the element
4myElm.style.color = 'red'; // Change the text color of the element
5
6document.body.appendChild(myElm); // Add the object to the DOM
1
2 var para = document.createElement("P"); // Create a <p> element
3
4 para.innerText = "This is a paragraph"; //
5 Insert text
6document.body.appendChild(para); // Append <p> to <body>
1var btn = document.createElement("BUTTON"); // Create a <button> element
2btn.innerHTML = "CLICK ME"; // Insert text
3document.body.appendChild(btn); // Append <button> to <body>
1document.body.onload = addElement;
2
3function addElement () {
4 // create a new div element
5 var newDiv = document.createElement("div");
6 // and give it some content
7 var newContent = document.createTextNode("Hi there and greetings!");
8 // add the text node to the newly created div
9 newDiv.appendChild(newContent);
10
11 // add the newly created element and its content into the DOM
12 var currentDiv = document.getElementById("div1");
13 document.body.insertBefore(newDiv, currentDiv);
14}