xxxxxxxxxx
// main div child of body
const mainDoc = document.getElementById("main");
/**
* Creates a new DOM element and appends it to a specified parent element.
*
* @param {string} element - The type of DOM element to create (e.g., 'div', 'span', 'p').
* @param {HTMLElement} where - The parent element to which the new element will be appended.
* @param {string|false} content - Optional. The content to be added to the new element as text. Defaults to false.
* @returns {HTMLElement} The newly created DOM element.
*/
const newElementDom = (element, where, content = false) => {
// Create the specified element
const newDiv = document.createElement(element);
// If content is provided, create a text node and append it to the new element
if(content){
const newContent = document.createTextNode(content);
newDiv.appendChild(newContent);
}
// Append the new element to the specified parent element
where.appendChild(newDiv);
// Return the newly created element
return newDiv;
};
// register new element in variable
let pText = newElementDom("p", mainDoc,"hello world");
// register div in variable
let div1 = newElementDom("div", mainDoc);
console.log("New Element Dom: ", pText, div1);
xxxxxxxxxx
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
xxxxxxxxxx
var newDiv = document.createElement("div");
document.body.appendChild(newDiv);
xxxxxxxxxx
// Create a new element
const newElement = document.createElement("div");
// Set attributes or properties of the element
newElement.id = "myElement";
newElement.className = "my-class";
newElement.textContent = "This is a dynamically created element";
// Append the element to the document body or any other parent element
document.body.appendChild(newElement);
xxxxxxxxxx
const box = document.createElement("div");
box.id = "box";
document.body.appendChild(box);
xxxxxxxxxx
// Create a new <div> element
var newElement = document.createElement("div");
// Set attributes (if needed)
newElement.id = "myElement";
newElement.className = "myClass";
// Set inner HTML (if needed)
newElement.innerHTML = "This is a new element";
// Append the new element to an existing element in the document
document.getElementById("parentElement").appendChild(newElement);