This week from Colt Steele The Web Developer Bootcamp, I focused on Dom Manipulation.
Document Object Model is the interface between JavaScript and HTML/CSS.
The browser turns every tag into a JavaScript object that we can manipulate.
Everything is stored inside of the document object.
Console.dir(document)
dir will print out the entire document.
The key strategy to success is to SELECT an HTML element and then MANIPULATE that HTML element.
It is possible to change the color of a h1 tag using JavaScript.
var h1 = document.querySelector(h1)
h1.style.color = 'pink'
DOM SELECTORS
document.URL, document.head, document.body, document.links
Methods
document.getElementById() - takes a string argument and returns the one element with a matching ID.
document.getElementsByClassName() - takes a string argument and returns a list of elements that have a matching class. Returns a list not an array. Contains every element on the page that matches the given class name provided.
document.getElementsByTagName() - returns a list of all elements of a given tag name like li or h1
document.querySelector() - returns the first element that matches a given css style selector like #color.
document.querySelectorAll() - returns a list of elements that matches a given css style selector.
Dom Manipulation
Changes an element style
adds/removes classes
changing the content of a tag
changes attributes
Style property is a way to manipulate an element style. The style property can style color, borders, font-size, background, and margin.
syntax: tag.style.color = 'blue'
classList is a read-only list that contains the classes for a given element. It is not an array, rather than directly manipulating the style with JavaScript, we can define a css class and then toggle it on or off with JavaScript.
textContent and innerHTML are both ways to grab the content of a given element. textContent returns a strong of all the text contained in a given element. innerHTML is similar to textContent, except it returns a string of all the HTML contained in a given element. textContent only gets the text no HTML because it treats everything as text. innerHTML treats everything as HTML.
Attributes
getAttribute() and setAttribute are used to read and write attributes like src and href.
Dom Events is Interactive
First, select an element and then add an event listener to it.
It is possible to listen for clicks like with a button, hover over an element like h1 element, and keypresses with text input.
The method to use is addEventListener()
element.addEventListener(type, functionToCall)
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
https://www.w3schools.com/js/js_htmldom.asp
Top comments (0)