What is the DOM?:
First, we need to know what DOM is.
DOM stands for:
It is a programming interface for HTML and XML documents. It defines the logical structure of documents and the way a document is accessed and manipulated. The DOM structure is similar to that of an upside down tree with “document” being at the top. The “DOM” tree structure represents the HTML of the website, and every HTML element is considered to be a node.
There are many ways to manipulate the DOM, but the first step is actually setting up the script tag. The script tag should be placed inside the index.html file (very similar to setting up a CSS styling sheet). The script tag should be placed right above the closing body tag. Here’s an example of this:
An alternative could be placing the
<script> tag inside the
<head> tag and place the
defer attribute between the words script and type:
defer attribute tells the browser not to wait for the script. Instead, the browser will continue to process the HTML, build the DOM. The script loads “in the background”, and then runs when the DOM is fully built. Whichever way you choose to write the script tag, both should be fine.
Accessing Elements Inside the DOM:
document.getElementById()➞ using this method can find a single element by its id
document.getElementsByClassname()➞ returns an HTML collection which contains every descendant element that has the specified class name.
document.getElementsByTagName()➞ similar to
getElementByClassname(), this method returns an HTML collection that includes each descendant with the specific HTML tag.
document.querySelectorAll()➞ returns a node list representing document’s elements that match the specified group of selectors.
document.querySelector()➞ This is my favorite way to access a specific node because you can literally access anything on the DOM whether it is with an id or tag.
Creating & Manipulating Elements:
Create ➞We can create an element by using
After creating an element, we can either add something in it or update using
textContent. For more info on how to use either of the three check the resources section at the bottom of this blog!
Adding to the DOM:
After querying for an element or simply just creating and then adding something or updating what’s inside, we finish the process by appending those changes. When we append, we’re usually just adding a child element into its parent. There are 2 ways to do this:
Either way is fine, I personally like using
.append() because it’s easier to remember.