The Document Object Model is the interface where JS meets HTML and CSS.
// Select an element
var header = document.querySelector("h1");
// Manipulate the selection
header.style.color = "rebeccapurple";
// Select an element
var body = document.querySelector("body");
var isPurple = false;
// Manipulate the selection
setInterval(function(){
if(isPurple) {
body.style.background = "coral";
} else {
body.style.background = "rebeccapurple";
}
isPurple = !isPurple;
}, 2000);
Everything revolves around the document.
// Pure JS
var tag = document.getElementById("highlight");
tag.style.color = "black";
tag.style.background = "yellow";
tag.style.fontSize = "3em";
tag.style.marginTop = "1em";
// ******************************************
// Alternative with CSS classes
// CSS
.some-class {
color: black;
background: yellow;
font-size: 3em;
margin-top: 1em;
}
// JS
var tag = document.getElementById("highlight");
// Add class
tag.classList.add("some-class");
// Remove class
tag.classList.remove("some-class");
// Check if has class and toggle
tag.classList.toggle("some-class");
var tag = document.querySelector("p");
// Retrieve content
tag.textContent; // "This is a paragraph."
// Change content
tag.textContent = "This is the new text, ha!";
var link = document.querySelector("a");
link.getAttribute("href");
// a href="www.blabla.com"
link.setAttribute("href", "http://www.dogs.com");
// a href="http://www.dogs.com"
var img = document.querySelector("img");
img.setAttribute("src", "cats.png");
// img src="cats.png"
Making things interactive.
We first SELECT and element and then add an EVENT LISTENER to it.
EX. "Listening for a click on a specific button"
element.addEventListener(type, functionToCall);
var btn = document.querySelector("button");
btn.addEventListener("click", function() {
console.log("Hey! stop clicking on me!");
});
:( No one has clicked on me...
There are hundreds and hundreds of events, you can see them all HERE.