MSH
0
Q:

document create element

var newDiv = document.createElement("div");
document.body.appendChild(newDiv);
11
//create and append element
 var node = document.createElement("LI");                 // Create a <li> node

 var textnode = document.createTextNode("Water");         // Create a text node

 node.appendChild(textnode);                              // Append the text to <li>

 document.getElementById("myList").appendChild(node);     // Append <li> to <ul> with id="myList" 
8
let myElm = document.createElement("p");	// Create a new element

myElm.innerText = 'test';		// Change the text of the element
myElm.style.color = 'red';		// Change the text color of the element

document.body.appendChild(myElm);	// Add the object to the DOM
0
// A function to create elements in JS
function elementFactory(tag, text) {
    const el = document.createElement(tag);
    el.textContent = text;
    return el;
}

const someListItem = elementFactory("li", "some text"); 
1
document.body.onload = addElement;

function addElement () { 
  // create a new div element 
  var newDiv = document.createElement("div"); 
  // and give it some content 
  var newContent = document.createTextNode("Hi there and greetings!"); 
  // add the text node to the newly created div
  newDiv.appendChild(newContent);  

  // add the newly created element and its content into the DOM 
  var currentDiv = document.getElementById("div1"); 
  document.body.insertBefore(newDiv, currentDiv); 
}
0

New to Communities?

Join the community