Dom create new html element
You can create a new HTML element using the document.createElement()
method. Here's an example:
const newElement = document.createElement("div");
This will create a new <div>
element.
You can also specify the element type as a string, like this:
const newElement = document.createElement("span");
This will create a new <span>
element.
You can also add attributes to the new element using the setAttribute()
method:
const newElement = document.createElement("div");
newElement.setAttribute("id", "myDiv");
newElement.setAttribute("class", "myClass");
This will create a new <div>
element with an id
attribute set to "myDiv" and a class
attribute set to "myClass".
You can also add content to the new element using the innerHTML
property:
const newElement = document.createElement("div");
newElement.innerHTML = "Hello World!";
This will create a new <div>
element with the text "Hello World!" inside it.
Finally, you can append the new element to the DOM using the appendChild()
method:
const newElement = document.createElement("div");
newElement.innerHTML = "Hello World!";
document.body.appendChild(newElement);
This will create a new <div>
element with the text "Hello World!" inside it and append it to the <body>
element of the HTML document.
Here is the full code:
const newElement = document.createElement("div");
newElement.innerHTML = "Hello World!";
document.body.appendChild(newElement);
This will create a new <div>
element with the text "Hello World!" inside it and append it to the <body>
element of the HTML document.