- Create DOM elements programmatically
- Add elements in the DOM
- Update elements using
innerHTML
- Change properties on DOM nodes
- Remove elements from the DOM
In this lab, you will be inserting, altering, and removing DOM nodes. You will be doing the following:
- Ask the DOM to find an HTML element or elements in the rendered page
- Remove or insert the selected element(s) and / or
- Adjust a property of the selected element(s)
You've come to understand the DOM and have powerful tools for selecting the right elements. You now want to understand creating new nodes, deleting nodes, and updating nodes' properties.
Creating an element in JavaScript is an easy process. Simply call
document.createElement('tagName')
, where tagName
is the name of any valid HTML
tag (e.g., 'p'
, 'div'
, 'span'
, etc.).
Open index.html
file in your browser and open up the browser's console. In the
console, enter
var element = document.createElement('div')
The element doesn't show up on the page. Why not?
To get an element to appear in the DOM, we have to append
it to an existing
DOM node. To go back to our tree metaphor, we have to glue our new leaf onto a
branch that's already there. We can start as high up on the tree as
document.body
, or we can find a more specific element using any of the
methods we've learned for traversing the DOM.
Let's append element
to body
to start:
document.body.appendChild(element)
We can continue to update element
, since we have a reference to it:
var ul = document.createElement('ul')
for (let i = 0; i < 3; i++) {
let li = document.createElement('li')
li.innerHTML = (i + 1).toString()
ul.appendChild(li)
}
element.appendChild(ul)
Creating elements and then appending them into the DOM is a multi-step process. It's also the safest and most reliable. Most repeated code can be removed by using functions and loops. It's The Right Way.
That said, there's another route which is commonly used, Element.innerHTML
. If you can get a node with
getElementById
or querySelector
or any of the modes you've learned, you can imagine that you've gotten that node's opening and closing HTML tag. You can update that node's innerHTML
property with a string of HTML and it will be just as if you changed the HTML source for that node.
let element = document.querySelector("p#greeting");
element.innerHTML = 'Hello, DOM!'
If there is a <p>
aragraph with id
of greeting
, our code will grab that and assign it to element.
What would you write in HTML to put 'Hello, DOM!'
between those <p>
tags? Why you'd put the plain text 'Hello, DOM!
?
For a slightly more complicated example:
let header = document.getElementById("div#header");
header.innerHTML = "<h1>Poodles!</h1><h3>An Essay into the Pom-Pom as Aesthetic Reconfiguration of the Other from a post-Frankfurt School Appropriationist Perspective</h3><p><em>By: Byron Q. Poodle, Esq., BA.</em></p>";
This creates, with JavaScript, in the DOM, the quivalent of:
<div id="header">
<h1>Poodles!</h1>
<h3>An Essay into the Pom-Pom as Aesthetic Reconfiguration of the Other from a post-Frankfurt School Appropriationist Perspective</h3>
<p><em>By: Byron Q. Poodle, Esq., BA.</em></p>
</div>
There are dangers with using innerHTML
, however. If you put user-derived data into the DOM using innerHTML
, someone could do something nasty. Consider the following code:
content = someTextArea.value
node.innerHTML = `Hi, ${content}!`
We might have intended for someTextArea
to contain something like a person's name that we're going to echo back out to the screen.
But what if the person typing in someTextArea
is a nasty person and submits:
<a href='#' onclick='doSomethingNastyLikeStealCookies'>Click here to claim your prize!</a>
While you're not familiar with events (yet!), it should be clear that doSomethingNasty
when clicking on a link that promises a prize is probably not what users expected. While it can be guarded against, innerHTML
can accidentally lead to problems in sites. Be careful with it!
We can change properties on DOM nodes to change their appearance.
element.style.backgroundColor = '#27647B';
You've changed what's on the screen!
Feel free to set as many properties as you'd like โ this is a good chance to look around and explore different properties of DOM elements.
Let's adjust the display:
element.style.textAlign = 'center';
ul.style.textAlign = 'left'
That's better.
We know how to add things. What if we want to remove an element from a page?
Let's really use the power of querySelector
and method chaining.
The removeChild()
method requires us to find a parent and tell it to remove
its already-found child:
ul.removeChild(ul.querySelector('li:nth-child(2)'))
The second element is gone!
What if we want to remove the whole unordered list (ul
)?
We can just call remove()
on the element itself:
ul.remove()
And it's gone!
You now know how to create, append and remove elements in the DOM with JavaScript. With this knowledge, you can become a master DOM manipulator in no time.
View Creating and Inserting DOM Nodes on Learn.co and start learning to code for free.