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
divwith anidofroot
- 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#rootwithdocument.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
divwithdocument.createElement('div')- and assign it to a variable (
element) - Finally, define the
textContentofelementto 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
divwe created,- with
textContentandclassNamedefined
- 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)
<body> <div id="root"></div> <script type="module"> const rootElement = document.getElementById('root') const element = document.createElement('div') element.textContent = 'Hello JavaScript' element.className = 'greeting' rootElement.appendChild(element) </script></body>