Just as the DOM allows scripts to modify existing elements, it also allows for the creation of new ones.
.createElement(tagName) method creates a new element based on the specified tag name passed into it as an argument. However, it does not append it to the document. It creates an empty element with no inner HTML.
In order to create an element and add it to the web page, you must assign it to be the child of an element that already exists on the DOM. We call this process appending. The
.appendChild() method will add a child element as the last child node.
The following code creates a new paragraph element, gives it an
id, adds text to the new element’s
.innerHTML, and appends it to the body of the document:
let paragraph = document.createElement('p'); paragraph.id = 'info'; paragraph.innerHTML = 'The text inside the paragraph'; document.body.appendChild(paragraph);
.innerHTML property, the
.appendChild() method does not replace the content inside of the parent, in this case
body. Rather, it appends the element as the last child of that parent.
lielement using the
.createElement()method and save it in a variable called
On the following line, assign the element an id of
'oaxaca'by using the
Lastly, assign the element the text
'Oaxaca, Mexico'by using the
Append the new element you created as the last child of the list with the ID
Scroll to the bottom of the page in the browser to see your new element.