Dynamic Interfaces

We can create brand new HTML elements " on the fly " and insert them anywhere on the page without ever touching the actual HTML file!

1. Creation

To create a new element, use document.createElement:

let div = document.createElement('div');
div.className = "alert";
div.innerHTML = "<strong>Hello everyone!</strong>";

2. Insertion

Once an element is created, it only exists in your computer's memory. You must physically attach it to the DOM tree for it to appear on the screen:

  • parent.append(el): Adds to the END of the parent.
  • parent.prepend(el): Adds to the BEGINNING of the parent.
  • el.before(other): Inserts right BEFORE the element.
  • el.after(other): Inserts right AFTER the element.

Let's create a new button and add it to the body of the page! Type these commands one by one:

JS Console

Type: let btn = document.createElement('button'); btn.textContent = "I am alive!"; document.body.prepend(btn);

3. Deletion

If you want to remove an element, you don't need to ask its parent anymore. Just call remove() on the element itself:

JS Console

Type: document.querySelector('button').remove()

Note

All insertion methods automatically remove the element from its old place if it was already in the DOM. A single element cannot exist in two places at the same time!