The DOM is called the Document Object Model, and you can think of it as a large family tree with branches. Each branch is called a node, which connects to the elements on your HTML document. Basically, it turns your HTML document into the tree, with the parent elements branching off into their child branches.
<div class="container"> <div class="child1"></div> <div class="child2"></div> </div>
Above, the container
div is the parent and
child2 are the two children that branch off from the container
<script> element at the end of your HTML document, or you can connect an external file with the
head section to link it and defer it to later:
<script src="js-name-file.js" defer></script>
Each node is an object, so we can use various methods attached to them to manipulate the DOM. Below are some basics I’ve learned this weekend:
element.querySelector(selector) : references the first match of the selector in the DOM
element.querySelectorAll(selector) : returns a “nodelist” with references to all the matches of the selector.
const myDiv = document.createElement('div') : creates an element in memory only and saves it to a myDiv variable (this does not insert it into the DOM yet, you have to order it to do that with methods below).
parentNode.appendChild(childNode) : attaches the child node as the last one inside the parent node
parentNode.insertBefore(new, reference) : inserts the
new child into the parent node before the
parentNode.removeChild(child) : removes child from parent on the DOM
With references to an element (i.e. you saved the reference into a variable like we did with
myDiv above), you can use that reference to alter the element properties in the DOM.
myDiv.style.color = "blue"; myDiv.style.cssText = "color: red; background: black"; myDiv.setAttribute("style", "color: blue, background: white");
myDiv.classList.add("newClass"); myDiv.classList.remove("newClass"); myDiv.classList.toggle("newClass");
These three classList methods can add or remove classes from myDiv. In reality though, toggle is the one that’s most used and was recommended by The Odin Project. Toggle will add a class if it’s not already there, or it will delete it when called if the class is present. Basically it does the opposite of what is already in the DOM.
myDiv.textContent = "Hello World!"; myDiv.innerHTML = "<span>Hello World!</span>";
textContent is preferred to add text due to potential security risks with
innerHTML. innerHTML can insert HTML code into your site which can be used by bad actors and black hats to hack you or others.
- Select a node or create a new element and save it in a variable: this makes it easier to reference it later when adding styles or attributes.
- Add styles to the element or content
- Append your element to the parent, either at the end or before another element. I forgot to do this several times while practicing and kept wondering why I wasn’t seeing any changes on the actual screen.