What are some best JavaScript DOM practices?

When one develops a dynamic web app, they perform multiple DOM operations (e.g., adding a new element, updating the style of an element, or removing an element). While doing such a DOM operation, we can maintain some coding practice that will not affect the performance of our web app.

Use Class or ID selector

When searching an element from the DOM, use the class or id of the element instead of a common selector (like element name).

Example

 <ul>
   <li>Raj</li>
   <li>Ram</li>
   <li>Rahul</li>
</ul>

In JavaScript:

let li = document.querySelector("li"); 

// Instead of querying using the 'li' selector, use a class name like the one below 

let liByClassName = document.querySelectorAll(".user");

Query parent instead of document

When you’re searching an element in DOM, instead of searching in document, search in the parent element if the parent if the element is already cached.

let ul = document.querySelector('.users-list');

// we have parent element(ul) in our code, In this case instead of using 
let li = document.querySelectorAll(".user");

// we can use like this 
li = ul.querySelectorAll(".user");

Use fragment instead of directly appending elements

When you are dynamically appending new elements, instead of appending directly to the DOM node, use a fragment and then append it to the DOM.

let newUsers = ["Kamal", "Balaji", "Vinith", "Gokul"];

function withoutFragment(users){
   let ul = document.querySelector('.users-list');
   for(let i = 0, l = users.length; i < l; i++ ){
      li = document.createElement("li")
      li.textContent= users[i];
      ul.append(li);
   }
}

function withFragment(users){
   let ul = document.querySelector('.users-list');
   let fragment = document.createDocumentFragment();
   for(let i = 0, l = users.length; i < l; i++ ){
      li = document.createElement("li")
      li.textContent= users[i];
      fragment.append(li);
   }
   ul.append(fragment);
}

Instead of adding style directly, use a class with a predefined style

Imagine that you need to change the background color and text color of ul on mouseover.

let ul = document.querySelector('.users-list');

// Not recommended 
ul.addEventListener('mouseover', (ev)=>{
   this.style.color = "white";
   this.style.background="black"; 
});

In such a situation, you would define the style in the CSS file and use that.

// in css file 
.users-list-hover {
   color: white;
   background : black;
}
// in js 
let ul = document.querySelector('.users-list');

// Recommended Way  
ul.addEventListener('mouseover', (ev) => {
   this.classList.add("users-list-hover");
});

The above tips allow for you to efficiently write easy code.

Free Resources