The DOM
Which sounds scary and overbearing but it probably isn’t maybe.
The Document Object Model (DOM) is a programming interface for HTML and XML documents. It provides a structured representation of the document and it defines a way that the structure can be accessed from programs so that they can change the document structure, style and content. The DOM provides a representation of the document as a structured group of nodes and objects that have properties and methods. Essentially, it connects web pages to scripts or programming languages.
(From the Mozzilla docs)
This is a really wordy way to say that, in general, the DOM is a way to access the stuff on your page. It comes in two pieces.
- The document’s representation in computer memory. In essence, behind the scenes the DOM is all the visible (and invisible) stuff in your page stored in the computer’s memory so you can easily access it.
- A way to find and modify the things inside the DOM
Getting a reference to something in the DOM
Several methods (all inside of havascript)
- document.getElementsByTagName(“tagName”);
- document.getElementById(“id”);
- document.getElementsByClassName(“className”);
- document.querySelector(“#css .selector”);
All of these return a DOM Element (or an array of DOM elements) reference.
References
- When you are programming, variables are not the actual thing they contain
- Instead, variables are pointers to the actual thing
-
In other words, the variables you are working with are more like names than things
- I am a single entity
- But you might call me “Travis”, “Mr. Faas”, “Teacher”, “Teech”, or even “That guy”
- Those are all references to the entity that is me
References in Code
document.getElementById gets a reference to the DOM element. So, this is totally valid:
Both are references to myDiv, though neither of them actually are myDiv
Get element by ID
Get element by class name
- Return an array
DOM Elements
DOM element have some useful properties
- innerHTML
- style
- className
- parent
Inner HTML
- Changes the html within the tag
//changes the stuff within the tag
BEFORE
AFTER
Changing styles
Use the style property, and its sub properties
Style Caveat
The properties use camel-casing where CSS uses the dash
CSS background-color
JS backgroundColor
Class
Sometimes you might want to have a prestyled class and just add it to the DOM element at runtime. You can change its class name.
Creating new elements
document.createElement
- A way to create DOM elements before adding them to the DOM
- Takes one argument, a tag name
- Needs to be a valid tag
Styling newly created elements
Adding new elements
- domElementRef.appendChild
Removing elements
domRef.removeChild()