5 Tips for Manipulating the DOM
2) console.dir

You’ve probably seen console.log before. It’s one of the most well known debugging tools for breaking into your code and seeing what values are through the call stack. When manipulating the DOM, however, console.log with an element that resolves to an HTML element will sometimes leave information to be desired. If instead of the HTML element, we’d like to see the DOM node, we can use, console.dir. It will return the DOM node along with all its attributes and properties which includes helpful values such as the node’s children, parent, and classList.

The result of invoking console.dir on a DOM node.

3) Traversing the DOM with parentNode and childNodes

In addition to query selectors, traversing the DOM by working your way through a node’s ancestors and children can be very useful as well. This can come in handy when working with a form with multiple inputs. For example, if you have an event listener set up on the form’s submit button, you can move up to the shared parent (the form node) using parentNode. From the form node, you can then use childNodes which will return an array of the form’s children.

Using parentNode and childNodes

In the example above, e.target is the form button with the event listener, while pictureSrcValue and descriptionValue are both input values of the button’s text field siblings. In this example, we accessed this information to update the DOM and send a POST request to the backend.

4) Dataset

Saving information into class and ID attributes of elements can be useful if you plan on using it later. This can quickly become messy, however, when adding CSS attributes for style as well. Wouldn’t it be great if there was a node attribute made especially for this?

> Enter Dataset!

To use Dataset you first need to set it in the element. This is shown below on lines 65, 66, 67 and 68.

Setting dataset values

An element can have multiple data set values. In this example, we are referencing the count value stored in the dataset on line 81 and then casting it to an integer on line 82 before working with it in later code. We used the value of this dataset to keep track of reactions on posts in our app.

Accessing dataset values

5) Delegation

Delegation is the process of adding an event listener to a “stable parent” or parent node that will always be on the page and then restricting the listener’s recognition to a specific child node of the parent. In the example below, the “click” event listener is added to the “location container” node on line 77. On line 79, however, we have a condition that restricts the event listener’s activity to an event on a specific child. Here we only want children who have a class of “reaction-button” to trigger the listener’s functionality.

Applying the principle of delegation

Sources:
['Chris Liendo']
['JavaScript']