Intro
DOM is the interface between Javascript and HTML+CSS. The browser turns every HTML tag into a Javascript object that we can manipulate. Everything is stored inside the document object.
Select and manipulate
var h1 = document.querySelector("h1");
h1.style.color = "pink";
Select
document.getElementById()
document.getElementsByClassName()
document.getElementsByTagName()
document.querySelector()
- returns the first element that matches a given CSS-style selector
document.querySelector("#highlight")
document.querySelectorAll()
- return all matching elements
Manipulate
- changing an element’s style
- adding/removing classes
- changing the content of a tag
- changing attributes(src, href, etc.)
Style
var tag = document.getElementById(highlight);
// manipulate
tag.style.color = "blue";
tag.style.border = "10px solid red";
It’s recommended for styles to be defined in a separated file or files. So just use js to turn on or off, switch between styles.
.some-class {
color: blue;
border: 10px solid red;
}
var tag = document.getElementById(highlight);
// add the css class
tag.classList.add("some-class");
//remove
tag.classList.remove("another-class");
//toggle
// if the tag has the class name, remove it
// else, turn it on
tag.classList.toggle("another-class");
Text and content
textContent
will return a string of all the text contained in a given element.innerHTML
is similar, but it returns a string of all HTML contained in a given element.
<p> This is a <strong>good</strong> para</p>
var tag = document.querySelector("p");
// Retrieve the text
tag.textContent; // This is a good para
tag.innerHTML; // This is a <strong>good</strong> para
// alter
tag.textContent = "new";
tag.innerHTML = "<strong>goodbye</strong>";
Attributes
Use getAttribute()
and setAttribute()
to read and write attributes like src
or href
.
<a href="www.google.com">link</a>
<img src="logo.png">
var link = document.querySelector("a");
link.getAttribute("href");
link.setAttribute("href", "http://www.facebook.com");
Events
- Click on a button
- Hovering over a link
- Dragging and dropping
- Pressing the enter key
Process is that we select an element and then add an event listener. Multiple listeners can be added.
List of events ref: https://developer.mozilla.org/en-US/docs/Web/Events
element.addEventListener(type, functionToCall);
// example
var button = document.querySelector("button");
button.addEventListener("click", function() {
console.log("CLICKED");
});
Example events
mouseover
: the moment that mouse starts being on the elementmouseout
: the moment that mouse leaves the elementinput
: the value of input tag changes