Intro to the DOM
Finally, JS meets HTML+CSS
Objectives
- Define what the DOM is
- Understand why DOM Manipulation is awesome
- List a few examples of sites that use JS to manipulate the DOM
- Understand the SELECT, then MANIPULATE workflow
Why Should You Care?
- Games
- Scrolling Effects
- Dropdown menus
- Form Validations
- Interactivity
- Animations
- Every awesome site ever
A few examples:
The DOM
Document Object Model
The Document Object Model is the interface between your Javascript and HTML+CSS
<!DOCTYPE html>
<html>
<head>
<title>My title</title>
</head>
<body>
<a href="someLink">My link</a>
<h1>My header</h1>
</body>
</html>
The browser turns every HTML tag into a Javascript object that we can manipulate
Everything is stored inside of the document object
The Process
SELECT an element and then MANIPULATE
<!DOCTYPE html>
<html>
<head>
<title>My title</title>
</head>
<body>
<a href="someLink">My link</a>
<h1>My header</h1>
</body>
</html>
For our example, we'll change the <h1> color using JS
The Process
SELECT an element and then MANIPULATE
var h1 = document.querySelector("h1");
SELECT the <h1> and save to a variable
The Process
SELECT an element and then MANIPULATE
var h1 = document.querySelector("h1");
h1.style.color = "pink";
MANIPULATE using the <h1> we selected
One more example
SELECT the <body> and change its color every second
var body = document.querySelector("body"); //SELECT
var isBlue = false;
setInterval(function(){ //MANIPULATE
if (isBlue) {
body.style.background = "white";
} else {
body.style.background = "#3498db";
}
isBlue = !isBlue;
}, 1000);
Intro to the DOM
By Colt Steele
Intro to the DOM
- 25,270