Master the DOM

It’s not as hard as you might think

Juha Lindstedt
Sep 29, 2016 · 4 min read

Introduction

DOM is not that hard and especially not slow.

Creating elements

const h1 = document.createElement('h1')// <h1></h1>

Modifying text content

h1.textContent = 'Hello world!'// <h1>Hello world!</h1>

Attributes

h1.setAttribute('class', 'hello')// <h1 class="hello">Hello world!</h1>
h1.className = 'hello'// <h1 class="hello">Hello world!</h1>
h1.classList.add('hello')// <h1 class="hello">Hello world!</h1>h1.classList.remove('hello')// <h1>Hello world!</h1>
h1.setAttribute('id', 'hello-world')h1.id = 'hello-world'// <h1 id="hello-world" class="hello">Hello world!</h1>
input.checked = true
// <input checked>
input.checked = false
// <input>
input.setAttribute(‘checked’, ‘’)
// <input checked>
input.removeAttribute('checked')
// <input>

Attach elements

document.body.appendChild(h1)// <body><h1>Hello world!</h1></body>

Remove elements

document.body.removeChild(h1)// <body></body>

Finding elements

Insert in-between elements

/*
* <body>
* <script src="main.js"></script>
* </body>
*/
document.body.insertBefore(h1, document.body.firstChild)/* <body>
* <h1>Hello world!</h1>
* <script src="main.js"></script>
* </body>
*/

Create list of elements

Update list of elements

setChildren(login, [
email,
!forgot && pass
])

RE:DOM

import { el, text, mount } from 'redom'class Hello {
constructor () {
this.el = el('h1.hello',
{ onclick: e => this.onclick(e) }
'Hello ',
this.target = text('world'),
'!'
)
}
update (data) {
this.target.textContent = data
}
onclick (e) {
console.log('clicked ', this)
}
}
const hello = new Hello()mount(document.body, hello)hello.update('you')
import { el, list, mount } from 'redom'class Td {
constructor () {
this.el = el('td')
}
update (data) {
this.el.textContent = data
}
}

const Tr = list.extend('tr', Td)
const Table = list.extend('table', Tr)

const table = new Table

mount(document.body, table)

table.update([
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
])

RE:DOM

RE:DOM blog

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store