HTML + JS = DOM (Document Object Model)
Table of Contents
HTML creates a document, JavaScript can access that document through a data structure called the DOM (or Document Object Model). This structure allows us to access each individual element as an object with a parent/child relationship or directly by ID using “getElementById“:
Accessing HTML elements with Javascript
After you have access to an Element, you can change it’s properties or call methods on. One example is to change the HTML that is within it by altering it’s innerHTML attribute.
var thediv = document.getElementById("mydiv");
thediv.innerHTML = "soemthing else";
Some other things that you might want to look over: createElement and appendChild
Manipulating Style Attributes
Using the DOM, you can manipulate any aspect of an HTML Element, including it’s CSS attributes such as visibility or background color:
var thediv = document.getElementById("mydiv");
thediv.style.backgroundColor = "red";
Events
JavaScript in the browser is very often event driven. This means that we can specify code to run when an event takes place. Some of these are driven by the browser doing it’s thing such as loading a page and some are driven by user interaction such as clicking a link or hovering over an element. Regardless of the type of event, we use the “addEventListener” method on all of the DOM elements to specify what to listen for and what code to run when the event is triggered.
element.addEventListener("event-name", functionToRun);
function functionToRun() {
// Code to execute
}
JavaScript HTML DOM EventListener
Load
The load event is very important as it is a way to specify what to do when a document is done loading, it also signifies when it is safe to call elements on the DOM:
function init() {
var thediv = document.getElementById("mydiv");
alert(thediv.innerHTML);
}
window.addEventListener("load", init);
Mouseover
var somediv;
function init() {
somediv = document.getElementById("some-div");
somediv.addEventListener("mouseover", makeblue);
somediv.addEventListener("mouseleave", makered)
}
function makeblue() {
somediv.style.backgroundColor = "#0000ff";
}
function makered() {
somediv.style.backgroundColor = "#ff0000";
}
window.addEventListener("load", init);