Creating new elements
In this chapter, you have seen so many cool ways to manipulate the DOM already. There is still an important one missing, the creation of new elements and adding them to the DOM. This consists of two steps, first creating new elements and second adding them to the DOM.
This is not as hard as it may seem. The following JavaScript does just that:
let el = document.createElement("p");
el.innerText = Math.floor(Math.random() * 100);
document.body.appendChild(el);
It creates an element of type p
(paragraph). This is a createElement()
function that is on the document
object. Upon creation, you need to specify what type of HTML element you would want to create, which in this case is a p
, so something like this:
<p>innertext here</p>
And as innerText
, it is adding a random number. Next, it is adding the element as a new last child of the body. You could also add it to another element; just select the element you want to...