DevNotes
@devnotes ·
JavaScript Part 8: Change the page with the DOM
This is where JavaScript meets your HTML. The DOM is the browser's live model of your page, and changing it changes what people see, instantly, without a reload.
The page as a tree
When the browser reads your HTML, it builds a tree of objects, one for each element. <html> sits at the top, <body> inside it, and your headings and paragraphs inside that. This tree is the DOM, short for Document Object Model, and document is your way into it. JavaScript can find any element in it, then read it, change it, add to it or remove it.
Finding elements
querySelector takes a CSS selector, the same kind as in CSS Part 1, and returns the first match, or null if nothing matches. querySelectorAll returns every match, and you can loop over them with for...of.
If you get null, check two things: that the selector is spelt right, and that your script tag has defer (JavaScript Part 1), so it runs after the HTML exists.
Changing text
Changing styles with classes
You can set a style directly, like heading.style.color = "red", but switching classes is cleaner. Keep the looks in your CSS, and let JavaScript decide which class applies:
Attributes
Making new elements
createElement makes a new element, you fill it in, and append adds it to the page as the last child. item.remove() takes an element off the page.
A warning about innerHTML
You'll often see innerHTML used to set HTML from a string:
It works, but never use it with anything a user typed. If someone enters <img src=x onerror="alert('hacked')"> as their name and your code puts it on the page with innerHTML, the browser runs their code on your site. That attack is called XSS. For text, use textContent, which always shows exactly what was typed and never runs it.
Try it
On a page with a <ul id="menu">, loop over ["Notes", "Videos", "Books"] and create an <li> for each word, appended to the list. Then give the second item a class, and style that class in your CSS.
Next: JavaScript Part 9: Clicks, typing and forms
Join WIK to like and reply to DevNotes and see more like this.