Create new div javascript

Here are a few ways to create a new <div> element using JavaScript:

Method 1: Using the document.createElement method

var newDiv = document.createElement("div");

This method creates a new <div> element and returns it as a HTMLDivElement object.

Method 2: Using the document.createElement method with attributes

var newDiv = document.createElement("div");
newDiv.id = "myDiv";
newDiv.className = "myClass";

This method creates a new <div> element and sets its id and className attributes.

Method 3: Using the innerHTML property

var newDiv = document.createElement("div");
newDiv.innerHTML = "Hello World!";

This method creates a new <div> element and sets its innerHTML property to the string "Hello World!".

Method 4: Using the documentFragment method

var newDiv = document.createDocumentFragment();
newDiv.appendChild(document.createElement("div"));

This method creates a new DocumentFragment object and appends a new <div> element to it.

Method 5: Using the appendChild method

var parentDiv = document.getElementById("parentDiv");
var newDiv = document.createElement("div");
parentDiv.appendChild(newDiv);

This method creates a new <div> element and appends it to an existing <div> element with the id "parentDiv".

Once you have created the new <div> element, you can add it to the DOM using the appendChild method or the innerHTML property.

Here is an example of how you can use the appendChild method:

var parentDiv = document.getElementById("parentDiv");
var newDiv = document.createElement("div");
newDiv.innerHTML = "Hello World!";
parentDiv.appendChild(newDiv);

This code creates a new <div> element with the text "Hello World!" and appends it to the <div> element with the id "parentDiv".