Lecture 4: JavaScript: DOM Flashcards
Document Object Model
The DOM is how programs can access and modify HTML
How DOM sees HTML
The HTML DOM views an HTML doc as a tree structure
Each node in tree is an HTML element
Is DOM static?
The DOM is NOT STATIC, It is live and up to date
Modifying the DOM means the web page that is displayed is modified
To manipulate an element inside the DOM, you need to…
Select it first.
querySelector()
Which returns a reference to the First match. E.G. Let element1 = document.querySelector(“h1”
querySelectorAll():
returns a list of all matching element nodes
Use CSS selectors
Basic, combinators, and group all works, but you cannot use pseudo classes.
Ways to change HTML Elements
Let element = document.querySelector(“.container p”)
element.style.backgroundColor = “yellow”
element.textContent = “I don’t like blind text.”
element.innerHTML = “I don’t like <strong>blind</strong> text.
Add CSS Dynamically
element.classList.add(‘classname’)
You can really add any attribute: element.setAttribute(‘id’, ‘id_Name’)
Creating an Element
Create a new element: createElement(‘tag_Name’)
Then add it to the DOM by appending to an element: element.appendChild()
Remove Element
Call remove, super simple.
element.remove().
Example
Let hello = document.querySelector(“h2”);
hello.remove();
Including Javascript
<script src = “../js/script.js”></script>
Defer
Defer keyword when your code requires the HTML structure to be loaded.