DOM Manipulation in JavaScript | Interview Practice Guide

Unlock the Power of JavaScript with DOM Manipulation: Discover how DOM manipulation can transform your web development skills. The Document Object Model (DOM) is a crucial concept for creating dynamic and interactive web pages. By mastering DOM manipulation, you gain the ability to dynamically update the content, structure, and styling of your HTML documents. 

Whether you’re a beginner or looking to sharpen your skills, understanding DOM manipulation opens up endless possibilities for enhancing user experiences. Dive into our comprehensive guide to explore essential techniques, from creating and inserting elements to advanced manipulation practices, and elevate your JavaScript expertise.


Introduction to DOM and DOM Manipulation

DOM Manipulation in JavaScript | Interview Practice Guide
DOM Manipulation in JavaScript 

What is DOM?

The DOM, or Document Object Model, is like a bridge between your web page (HTML) and JavaScript. Think of it as a big tree where each part of the HTML document is a branch. JavaScript can use this tree to change the web page, making it interactive and dynamic.

Understanding the DOM Tree

Imagine your HTML document as a family tree:

  • The top part of the tree is the "root" (usually the <html> element).
  • From this root, branches grow (these are elements like <head> and <body>).
  • Each branch can have smaller branches or "leaves" (like <h1>, <p>, <div>, etc.).

This structure lets us navigate and change parts of the web page easily.

How Browsers Render the DOM

When you open a web page, the browser takes the HTML code and builds the DOM tree. Here's how it works in simple steps:

  1. The browser reads the HTML from top to bottom.
  2. It creates a DOM tree based on the HTML tags.
  3. Each tag becomes a node in the tree, connecting to other nodes according to their structure in the HTML.
  4. Once the tree is built, the browser uses it to display the web page on the screen.

Basics of DOM Manipulation

DOM manipulation means using JavaScript to change the web page. Here are some basic things you can do:

  • Select Elements: Find parts of the page (like a button or a paragraph) that you want to change.
  • Change Content: Modify the text or HTML inside an element.
  • Change Styles: Adjust the appearance by changing CSS styles.
  • Add or Remove Elements: Insert new elements into the page or remove existing ones.
  • Handle Events: Make things happen when the user interacts with the page (like clicking a button).

Selecting DOM Elements

When you want to work with parts of a web page using JavaScript, you need to select those parts first. Here are some common methods to select elements and best practices to use them.

These are the Methods to Select DOM Elements

1. getElementById:

  • Use this method to select an element with a specific id.
  • Example:
  • var header = document.getElementById('main-header');
    
    If your HTML has <h1 id="main-header">Welcome</h1>, this code selects the h1 element.

2. getElementByClassName:

  • Use this method to select all elements with a specific class name.
  • Example:
  • var items = document.getElementsByClassName('list-item');
    
    If your HTML has multiple <li class="list-item">Item</li>, this code selects all li elements with the class list-item.

3. getElementByTagName:

  • Use this method to select all elements with a specific tag name.
  • Example
  • var paragraph = document.getElementsByTagName('p');
    
    If your HTML has multiple <p>Text</p>, this code selects all p elements.

4. querySelector:

  • Use this method to select the first element that matches a CSS selector.
  • Example
  • var firstItem = document.querySelector('.list-item');
    
    If your HTML has multiple <li class="list-item">Item</li>, this code selects the first li elements with the class list-item.

4. querySelectorAll:

  • Use this method to select all elements with a specific tag name.
  • Example
  • var items = document.getElementsByClassName('list-item');
    
    If your HTML has multiple <li class="list-item">Item</li>, this code selects all li elements with the class list-item

Best Practices for Selecting Elements

  1. Use IDs for Unique Elements:
    • If you know there’s only one element, use getElementById for a fast and direct way to select it.
  2. Use Classes for Groups of Elements:
    • When you need to select multiple elements, use getElementsByClassName or querySelectorAll with a class selector.
  3. Be Specific with CSS Selectors:
    • When using querySelector or querySelectorAll, write clear and specific CSS selectors to avoid accidentally selecting unwanted elements.
  4. Minimize DOM Searches:
    • Store references to elements you use often in variables. This reduces the number of times you need to search the DOM, making your code faster.
  5. Use the Most Suitable Method:
    • Choose the method that best fits your needs. If you need one element, use getElementById or querySelector. For multiple elements, use getElementsByClassName, getElementsByTagName, or querySelectorAll.

By following these best practices, you’ll write clearer, faster, and more efficient JavaScript code when working with the DOM.

Modifying DOM Elements

Changing HTML Content: innerHTML vs. textContent. 

1. innerHTML

  • This Property allows you to change the HTML inside an Element.
  • Example: If you have a <div> and you want to add a paragraph inside it, you can use innerHTML.
  • code:
  • let div = document.getElementById('myDiv');
    div.innerHTML = '<p>This is a paragraph</p>';
    
    Note: innerHTML can insert HTML tags and will render them.

2. textContent

  • This Property changes only the text inside an element.
  • Example: If you want to change the text inside a <div> but don't need to add HTML tags, use textContent.
  • code:
  • let div = document.getElementById('myDiv');
    div.textContent = 'This is a plain text';
    
    Note: textContent inserts text as it is, without interpreting HTML tags.

Modifying Element Attributes: setAttribute and getAttribute

1. setAttribute

  • This method sets or changes an attribute of an element.
  • Example: To change the src attribute of an image:
  • code:
  • let img = document.getElementById('myImage');
    img.setAttribute('src', 'new-image.jpg');

2. getAttribute

  • This method retrieves the value of an attribute from an element.
  • Example: To get the href attribute of a link:
  • code:
  • let link = document.getElementById('mylink');
    let hrefValue = link.getAttribute('href');
    console.log(hrefValue); 

Adding and Removing classes: classList.add, classList.remove, classList.toggle

1. classList.add

  • This property Adds one or more classes to an element.
  • Example: To add a highlight class to a <div>
  • code:
  • let div = document.getElementById('myDiv');
    div.classList.add('highlight');

2. classList.remove

  • Removes one or more classes from an element.
  • Example: To remove the highlight class from a <div>:
  • code:
  • let div = document.getElementById('myDiv');
    div.classList.remove('highlight'); 

3. classList.toggle

  • Add this class if it is not present, and remove it if it is present.
  • Example: To toggle the highlight class on a <div>:
  • code:
  • let div = document.getElementById('myDiv');
    div.classList.toggle('highlight'); 

Styling Element: Changing Inline Styles and Using CSS Classes/

1. Changing Inline Styles:

  • You can change the style of an element directly by setting its style property
  • Example: To change the background colour of a <div>
  • code:
  • let div = document.getElementById('myDiv');
    div.style.backgroundColor='blue'; 
    
    //here more examples of style:
    div.style.backgroundColor = 'blue';
    div.style.color = 'white';
    div.style.width = '200px';
    div.style.height = '100px';
    div.style.padding = '20px';
    div.style.border = '2px solid black';
    div.style.borderRadius = '10px';
    div.style.boxShadow = '5px 5px 10px gray';
    div.style.textAlign = 'center';
    div.style.fontSize = '18px';
    div.style.cursor = 'pointer'; 

2. Using CSS Classes:

  • Instead of setting styles directly, you can define styles in a CSS class and apply that class to elements.
  • CSS:
  • .highlight {
        background-color: yellow;
        color: red;
    }
    

  • JavaScript (if you need to add the class dynamically):
  • let div = document.getElementById('myDiv');
    div.classList.add('highlight');

This way, modifying DOM elements involves changing content, attributes, classes, and styles, making the webpage dynamic and interactive.

Creating and Inserting Elements

Creating New Elements

To add new items to your webpage, you first need to create them. You can do this with document.createElement. This method lets you make a new HTML element that doesn’t yet appear on the page.

Example:


// Create a new paragraph element
var newParagraph = document.createElement('p');

// Set the text content of the new paragraph
newParagraph.textContent = 'Hello, this is a new paragraph!';

Inserting Elements into the DOM

Once you have created a new element, you need to place it on the page.

There are different ways to do this:

1. appendChild: Adds the new element as the last child of a parent element.

Example:

// Find an existing element to be the parent
var parentElement = document.getElementById('container');

// Add the new paragraph to the parent element
parentElement.appendChild(newParagraph);

2. insertBefore: Adds the new element before a specified existing child of a parent element.

Example:

// Create another paragraph to be inserted before
var anotherParagraph = document.createElement('p');
anotherParagraph.textContent = 'I am another paragraph!';

// Find the existing element to insert before
var existingElement = document.getElementById('existingChild');

// Insert the new paragraph before the existing one
parentElement.insertBefore(anotherParagraph, existingElement);

3. insertAdjacentHTML: Inserts HTML directly into a specified position relative to an existing element.

Example:

// Insert a new paragraph right after an existing element
parentElement.insertAdjacentHTML('beforeend', '<p>This is added with insertAdjacentHTML!</p>');

Cloning and Reusing DOM Elements

Sometimes, you may want to use the same element more than once. You can make a copy of an existing element using cloneNode.

Example:


// Clone the existing paragraph
var clonedParagraph = newParagraph.cloneNode(true);

// Add the cloned paragraph to the parent element
parentElement.appendChild(clonedParagraph);
 

In this example, cloneNode(true) make a copy of the entire element, including its content. If you pass false instead, it will only copy the element itself, not its content.

By using these methods, you can dynamically add, position, and reuse elements on your webpage, making it interactive and customizable.

Removing DOM Elements

Styling Element: Changing Inline Styles and Using CSS Classes/

1. Removing Elements: removeChild, remove:

When you want to get rid of elements from a webpage, you can use a couple of methods:

  • removeChild: This method is used when you want to remove an element that is a child of another element. Think of it like this: if you have a big box (parent element) and inside it, there are smaller boxes (child elements), removeChild helps you take one of those smaller boxes out of the big box.
  • Example:
  • 
    //The big box
    var parentElement = document.getElementById('parent');
    
    // The small box you want to remove
    var childElement = document.getElementById('child'); 
    
    // Removes the samll box from the big box
    parentElement.removeChild(childElement); 

  • remove: This method is used to directly remove an element from the webpage. It works like pulling the element out of the entire page without needing to reference its parent.
  • Example:
  • 
    //The element you want to remove
    var element = document.getElementById('elementToRemove');
    
    //Remove the element
    element.remove();