Create a User Interface with Vanilla JavaScript and DOM
We’re starting this adventure with a blank HTML file. So you know that I’ve got tricks up my sleave.
- Add a
<body>
,- and inside, a
div
with anid
ofroot
- and inside, a
- Then add a
script
,- with
type="module"
- with
That’s all the markup that we need. Let’s jump into the script.
- Get a reference to the
div#root
withdocument.getElementById('root')
- and assign it to a variable (
rootElement
)
- and assign it to a variable (
- To the
rootElement
, append a new element- We don’t have one. So let’s create one.
- Create a new
div
withdocument.createElement('div')
- and assign it to a variable (
element
) - Finally, define the
textContent
ofelement
to beHello, JavaScript!
- …and as an extra, define the
className
“greeting”.
- and assign it to a variable (
That’s all for the script. Let’s see what that did in the browser.
- In our browser, we see the text “Hello, JavaScript!“.
- When we open the concsole
- our
div#root
, - our
script
, - and when we zoom into root,
- the
div
we created,- with
textContent
andclassName
defined
- with
- the
- our
We now have:
- A JavaScript module
- That creates a DOM element (that defines a few properties)
- And appends it to the DOM (that we created with HTML)