DEV Community

Aaron McCollum
Aaron McCollum

Posted on • Updated on • Originally published at codingwithaaron.wordpress.com

Working with the DOM Part 1

This past week has been a lot of focus on JavaScript – learning mainly the fundamentals. Variables, arrays, loops, functions, data structures, and ES6 updates. I’ve split time between learning on The Odin Project and freeCodeCamp for this. I feel fCC has a lot of coding practice, with their whopping 111 exercises for basic JavaScript, while The Odin Project is a really nice supplement for it with some additional resources.

This weekend, I started learning about the DOM and how you can use JavaScript in a website. This has been a little harder, but it’s something super important and I want to make sure I get this before moving on to more advanced JavaScript and some frameworks.

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>
Enter fullscreen mode Exit fullscreen mode

Above, the container div is the parent and child1 and child2 are the two children that branch off from the container div in the DOM. This is where JavaScript can come into play.

If you’ve ever wondered, JavaScript doesn’t actually change your HTML document. It can’t insert code in there for you. What is does change is the DOM. The DOM is created after the browser parses through your HTML file. Once the DOM is created, the JavaScript you write for your website can then interact with it manipulate it. If you have ever created a basic HTML-only website and ran it in your browser, congratulations you have created a DOM!

As a quick tip when writing JavaScript for the browser, you should either write your JS inside your <script> element at the end of your HTML document, or you can connect an external file with the defer attribute so that it’s read after your HTML document has been read and the DOM has been created. If your JavaScript code runs before the DOM has been fully created, your methods won’t work since there might not be nodes created yet for them to work on. So put your JavaScript code at the bottom of your document, or use the following code snippet in 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:

Query Selectors

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.

Element Creation

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).

Appending Elements

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 reference child

Remove Elements

parentNode.removeChild(child) : removes child from parent on the DOM

Altering Elements

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");
Enter fullscreen mode Exit fullscreen mode

Working with Classes

myDiv.classList.add("newClass");
myDiv.classList.remove("newClass");
myDiv.classList.toggle("newClass");
Enter fullscreen mode Exit fullscreen mode

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.

Adding text and HTML content

myDiv.textContent = "Hello World!";
myDiv.innerHTML = "<span>Hello World!</span>";
Enter fullscreen mode Exit fullscreen mode

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.

From practicing this a little, below are three basic steps that you need to more-or-less do each time you write JavaScript to manipulate the DOM.

  1. 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.
  2. Add styles to the element or content
  3. 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.

That’s it for now! I’m taking it very slow through this section to really get this down. This is a big foundational part of JavaScript and web development, so I want to make sure I really understand this before I move on. I’ll keep writing about the DOM and some more things I learn later this week.

Top comments (0)