Document Object Model (DOM) Flashcards
Adding Javascript to…
Websites
Adding Inline Javascript (NOT GOOD PRACTICE. DON’T USE INLINE JS)
Inside the , add a onload=” ”
Example
Internal Javascript
Include a inside of the html
External Javascript
Include a with a src=” ”
The placement of the with the .js link matters!
Include CSS in the beginning, inside the
Include JavaScript at the bottom, just before the closing tag
Intro to the Document Object Model
Catalogs a webpage into individual models/objects where we can alter/manipulate its behaviour and style
Document is the root of the webpage
document.firstElementChild;
HTML Root of web page
document. firstElementChild.firstElementChild;
document. firstElementChild.lastElementChild;
Selecting HTML Elements with…
JavaScript
GetElementBy
(Broad selector)
Get elements by tag name (li, ul, h1, ….)
document.getElementsByTagName(< tag >);
Get elements by class name
document.getElementsByClassName(< className >);
Get element by id
document.getElementById(< id >);
Query Selector
(More complex and precise selector)
document.querySelector(< CSS Selector >);
Returns a singular html element
If the query selector obtains multiple elements, the querySelector only returns the first element
document.querySelectorAll( < CSS Selector > );
Returns a list of all the html elements that match the CSS Selector
Manipulating and Changing Styles of HTML Elements with JavaScript
Properties may, and often are, different than the css property.
To set the value, have to include the property in “ “
Changing style
.style. = “”;
Changing color
.style.color = “< color >”;
Separation of Concerns: Structure vs Style vs Behavior
CSS files should only be in charge of styling a webpage.
So we shouldn’t use DOM - Javascript to modify the style of a web page.
What we can do is, include a style modifier in the CSS file, and using DOM we can add a new class property for the .classList to add/modify styling of a html element.
.classList
Returns a list of the classes that are attached to the element
We can then add properties to the list, to further add new properties for a html element
.classList.add();
Add a new CSS style property
.classList.remove();
Remove a CSS style property
.classList.toggle();
Toggle’s a CSS style property on/off.
Text Manipulation and the Text Content Property
.textContent Returns the actual text string value .innerHTML Returns the html code Can also modify the html
Manipulating HTML Element Attributes
Attributes consist of things like, class=, href=, src=, …
.attributes
Returns the mapping of all the attributes
.getAttribute(“ < Attribute to get > ”);
.setAttribute(“ < Which attribute to change> ”, “ < Value to change the attribute to > ”);