DOM 101

Made by Antonija with 

What is document object model (DOM)?

Relations between nodes

Let's use example from the previous lesson and...

...click on the fork button

Targeting nodes

let paragraphs = document.getElementsByClassName("text-content");
// returns an array of all the elements with a class text-content
let mainHeading = document.getElementById("main-heading");
// returns a single object, a heading

Targeting nodes

let divs = document.getElementsByTagName("div");
// returns an array of all the div elements
let imageInArticle = document.querySelector("article > img");
// returns the first element that matches the query

Removing elements

let figures = document.getElementsByTagName("figure");
figures.remove()
let imageInArticle = document.querySelector("article > img");
imageInArticle.remove()

Add new element

let p = document.createElement("p");
let contentOfP = document.createTextNode("I am nice paragraph");
div.appendChild(contentOfP);
header.appendChild(p)

Change text in the element

let mainHeading = document.getElementById("main-heading");
mainHeading.innerHTML="Hello from the JS"

DOM events

Syntax

element.addEventListener("typeoflistener", function(){
    // your code here
})
let mainHeading = document.getElementById("main-heading");
mainHeading.addEventListener("click", function(){
  alert("Click")
});

Click listener

let mainHeading = document.getElementById("main-heading");
mainHeading.addEventListener("mouseover", function(){
  alert("Mouse over")
});

Mouseover listener

...plenty listeners

List of all the listeners

Extra homework