JavaScript HTML DOM

JavaScript HTML DOM

The Document Object Model (DOM) is a way that helps JavaScript to interact with the content of a webpage. It allows you to change, add, or remove elements like text, images, and links from a webpage. It is like a bridge that connects the HTML structure of a webpage to the JavaScript code that is running on it. In this blog, we will see how you can use DOM to improve your website.

Table of Contents:

What is the DOM?

The DOM (Document Object Model) is a programming interface for web documents. It represents the structure of a webpage like a tree of objects, where each part of the page, like text, images, or links, is an object that can be changed or updated. This allows you to update the webpage without reloading it.

How Does DOM Relate to JavaScript?

JavaScript and the DOM work together to make a web page more interactive. DOM is really important in the web development process. Let’s see how it helps in detail:

  1. Changes web pages using the DOM: With the help of DOM, you can update text, images, and other parts of the page very quickly, and you don’t need to refresh the whole page.
  2. Make web pages interactive: The DOM allows JavaScript to respond to the user’s actions, like clicking a button or filling out a form, which helps make the page more interactive.
  3. Access and change page elements: JavaScript uses the DOM to find things on the page, like headings or images, and then make changes to them, like changing the text or colors.

Understanding the DOM Structure

DOM represents the structure of a webpage like a tree, where different elements of the page are like branches. Let’s see how the DOM is organized:

1. DOM Tree Structure

DOM structure is like a tree where the root node is at the top, and everything else, like images, paragraphs, and links, are connected under it like branches. The tree structure makes it easy to organize and find different parts of the webpage.

2. Nodes, Elements, and Attributes

  • Nodes: In the DOM, everything is called a “node.” There are three main types of nodes:
    • Element Nodes: These are the HTML tags, like <p> or <div>.
    • Text Nodes: These are the actual words or text inside the HTML tags.
    • Attribute Nodes: These are extra details inside the HTML tags, like id=”header” or class=”main”.
  • Elements: Elements are the HTML tags (like <h1>, <p>, and <img>). You can change these elements using JavaScript.
  • Attributes: Attributes give extra information about elements. For example, the src attribute in an <img> tag tells the browser where to find the image.

3. The Root Node and Child Nodes

  • Root Node: The root node is the starting point of the DOM tree. It’s usually the <html> tag in an HTML page, and everything else is connected to it.
  • Child Nodes: These are the smaller parts of the webpage that come from the root node. For example, the <head> and <body> tags are child nodes of the <html> tag. Inside the <body>, elements like <p> or <img> are child nodes, too.

Simple Example of the DOM Tree

Simple Example of the DOM Tree

Manipulating the DOM with JavaScript

Now that you have learned the DOM structure, let’s see how you can access, modify, create, insert, and remove elements in the DOM using JavaScript.

Accessing DOM Elements

If you want to change something on a webpage, you first need to “find” the thing you want to change. These methods will help you do that.

1. getElementById(): This method will help find an element by its ID, like a unique name for an element.

Syntax:
let element = document.getElementById(‘myId’);

2. getElementsByClassName(): This method will help you find all elements with the same class.

Syntax:
let elements = document.getElementsByClassName(‘myClass’);

3. querySelector(): This is a very flexible way to select elements using CSS-style selectors like ID, class, or tag.

Syntax:
let element = document.querySelector(‘.myClass’);

4. querySelectorAll(): This works like querySelector(), but it will give you all the elements that match the selector.

Syntax:
let elements = document.querySelectorAll(‘.myClass’);

Modifying DOM Elements

Once you have found the element that you want to change, you can change it in many different ways.

1. Changing text content: You can change the content inside an element, like a text or a heading, by using innerText.

Syntax:
let element = document.getElementById(‘myId’);
element.innerText = ‘New text here!’;

2. Modifying attributes: You can change attributes like links or images by using setAttribute().

Syntax:
let link = document.getElementById(‘myLink’);
link.setAttribute(‘href’, ‘https://www.newurl.com’);

3. Adding/Removing HTML elements: You can add new elements like a new paragraph or remove existing ones.

Syntax (To add an new element):
let newElement = document.createElement(‘p’);
newElement.innerText = ‘I am a new paragraph!’;
document.body.appendChild(newElement);

Syntax (To remove an element):
let elementToRemove = document.getElementById(‘removeMe’);
document.body.removeChild(elementToRemove);

Inserting and Removing Elements

You can control where the new elements will go, like adding them in the right place.

1. appendChild(): It adds a new element at the end of an existing element.

Syntax:
let newItem = document.createElement(‘li’);
newItem.innerText = ‘New list item’;
let list = document.getElementById(‘myList’);
list.appendChild(newItem);

2. removeChild(): It removes an existing element from the page.

Syntax:
let itemToRemove = document.getElementById(‘itemToRemove’);
let list = document.getElementById(‘myList’);
list.removeChild(itemToRemove);

3. insertBefore(): It allows you to add a new element before an existing one.

Syntax:
let newItem = document.createElement(‘li’);
newItem.innerText = ‘This comes before another item’;

let list = document.getElementById(‘myList’);
let firstItem = document.getElementById(‘firstItem’);
list.insertBefore(newItem, firstItem);

Example:
Let’s see an example using the above methods:




  
  
  DOM Manipulation Example


  

Original Heading

This is a description.

  • First item
// Accessing elements let header = document.getElementById('header'); let description = document.querySelector('.description'); // Changing text content header.innerText = 'Updated Heading'; description.innerText = 'This description has been updated!'; // Adding a new element let newItem = document.createElement('li'); newItem.innerText = 'New list item'; document.getElementById('myList').appendChild(newItem); // Add a new item when the button is clicked document.getElementById('addItemBtn').addEventListener('click', function() { let newItem = document.createElement('li'); newItem.innerText = 'Another new item'; document.getElementById('myList').appendChild(newItem); });

Output:

Updated Heading Output

Here,

  • The heading changes to “Updated Heading“.
  • The description paragraph is updated with new text.
  • A new list item is added to the list automatically when the page loads.
  • Every time the Add List Item button is clicked, a new list item is added to the page.

Event Handling in the DOM

Event handling helps you to add interactivity to a webpage, like clicking buttons and pressing keys. Let’s see the key concepts of event handling.

Understanding DOM Events

DOM events are actions that happen in a web page. These actions include:

  • Clicking a button
  • Typing on the keyboard
  • Moving the mouse over an element

When an action like this happens, the browser creates an event that you can respond to using JavaScript.

Event Listeners and Handlers

In JavaScript, event listeners and event handlers are used to handle user actions on the web page, like clicking buttons, pressing keys, etc.

1. addEventListener()

addEventListener() is a way to ‘listen’ for events, like clicking buttons, etc. This method helps you to run a function when an event happens.
Example: If you want to show a message when someone clicks a button.


    
        let button = document.getElementById('myButton');
        button.addEventListener('click', function() {
            // Show an alert when the button is clicked
            alert('Button clicked!');
        });
    

Output:

addEventListener Output

2. Event Propagation: Capturing vs Bubbling

When an event happens, it moves through the page in two ways:

  • Bubbling: The event starts at the element, like the button, and moves up to the parent elements, like a div.
  • Capturing: The event starts from the outermost element, like the document, and moves towards the specific element, like the button.

Note: By default, most events use bubbling, but you can change it if needed.

Common Events

Here are some common events you can use:

  • click: It happens when you click on an element.
  • keyup: It happens when you release a key on the keyboard.
  • keydown: It happens when you press a key down.
  • mouseover: It happens when the mouse hovers over an element.

Event Delegation

Event Delegation is a technique where you attach a single event listener to a parent element, and it handles the events for the child elements. You can do this by using event bubbling, where events move up the DOM from child elements to their parents.

Example:




    
    Event Delegation


    
  • Item 1
  • Item 2
  • Item 3
document.getElementById('item-list').addEventListener('click', function(event) { if (event.target && event.target.matches('li.item')) { alert('You clicked on: ' + event.target.textContent); } });

Output:

Event Delegation

Here,

  • The ‘click event is attached to the parent ‘ul’.
  • When a child ‘li’ is clicked, the event moves up to the parent, and the listener checks if the target is a ‘li’ with the class ‘item’.

DOM Traversal

DOM traversal means navigating through the HTML structure of the document to find and manipulate elements like text and tags. JavaScript gives you many tools to move through the structure and access different parts of the page.

Traversing Through DOM Nodes

Everything is a node in the DOM tree. There are different types of nodes:

  • Element nodes: These represent HTML tags (like <div>, <p>, etc.).
  • Text nodes: These contain the text inside HTML elements.
  • Attribute nodes: These represent the attributes of elements (like id, class, etc.).

Traversing through DOM nodes includes accessing parent, child, and sibling nodes to navigate the DOM structure.

Methods for Traversing the DOM

Here are the main methods that help you move through the DOM:

1. parentNode: The parentNode property helps you find the parent element of the current element.

Syntax:

let element = document.getElementById(‘childElement’);

let parent = element.parentNode;

console.log(parent);

2. childNodes: The childNodes property gives you all the child nodes of an element, which are text nodes like spaces and newlines, and comment nodes.

Syntax:

let parent = document.getElementById(‘parentElement’);

let children = parent.childNodes;

console.log(children);

3. nextSibling: The nextSibling property helps you find the next sibling node, which is the next node after the current one.

Syntax:

let currentNode = document.getElementById(‘currentElement’);

let next = currentNode.nextSibling;

console.log(next);

4. previousSibling: The previousSibling property helps you find the previous sibling node, which is the node just before the current one.

Syntax:

let currentNode = document.getElementById(‘currentElement’);

let previous = currentNode.previousSibling;

console.log(previous);

Navigating the DOM Tree Efficiently

When navigating the DOM, always use the correct method to find what you are looking for. For example, if you want only the child elements without text or comments, then use children instead of childNodes. And if you want to find the next or previous element and not text, then use nextElementSibling or previousElementSibling.

Example:




    
    
    DOM Traversal


    

Paragraph 1

Paragraph 2

Paragraph 3

Nested Paragraph

// Select an element (in this case, the first paragraph) let firstParagraph = document.querySelector('p'); // parentNode let parent = firstParagraph.parentNode; console.log("Parent of first paragraph:", parent); // childNodes (all nodes including text and comment nodes) let childNodes = parent.childNodes; console.log("Child nodes of parent (including text and comments):", childNodes); // children (only element nodes) let children = parent.children; console.log("Element children of parent:", children); // nextSibling let nextSibling = firstParagraph.nextSibling; console.log("Next sibling (can be text or element):", nextSibling); // previousSibling let previousSibling = firstParagraph.previousSibling; console.log("Previous sibling (can be text or element):", previousSibling); // firstElementChild let firstChild = parent.firstElementChild; console.log("First child element of parent:", firstChild); // lastElementChild let lastChild = parent.lastElementChild; console.log("Last child element of parent:", lastChild);

Output:

Navigating the DOM Tree Efficiently

Best Practices for DOM Manipulation

When working with JavaScript DOM manipulation, there are many best practices that can help you avoid common mistakes, organize your code, and improve performance. Let’s see them in detail:

Avoiding Common Mistakes

  • Don’t change the DOM too often: If you change the DOM too many times, it can slow things down. What you can do is group your changes together and update them all at once.
  • Don’t keep querying the DOM: If you are searching for elements repeatedly, it can be inefficient. You can save a reference to elements that you use often.
  • Avoid using innerHTML: Using innerHTML can be slow and insecure. It’s better to use safer and faster methods like modifying text content or creating elements directly.

Organizing Your Code for Efficient DOM Access

  • Use event delegation: Instead of adding event listeners to every individual element, you can add one listener to a parent element. It is more effective when you are working with many items.
  • Separate your code into components: Break your code into smaller reusable parts that handle specific tasks. It will make your code easier to organize.

Improving Performance

  • Use requestAnimationFrame for animations: This will help you create smoother animations by syncing them with the browser’s rendering process.
  • Avoid changing layout properties repeatedly: Changing properties like width and height multiple times can cause performance issues. You can use properties like transform or opacity that are more adaptable.
  • Use classList for class management: Use classList to add, remove, or toggle CSS classes, instead of changing the entire className, which can overwrite other classes.
  • Optimize for text: If you just need to change text, then you can use methods like textContent instead of innerHTML for better performance.
  • Handle events efficiently: For events that trigger frequently, like scrolling or resizing, you can use techniques like debouncing to limit how many times they are used, which will help you improve performance.

Conclusion

So in this blog, we have learned how you can use DOM to improve your website. The Document Object Model (DOM) is a way that helps JavaScript to interact with the content of a webpage. It is like a bridge that connects the HTML structure of a webpage to the JavaScript code that is running on it.

FAQs

About the Author

Senior Associate - Digital Marketing

Shailesh is a Senior Editor in Digital Marketing with a passion for storytelling. His expertise lies in crafting compelling brand stories; he blends his expertise in marketing with a love for words to captivate audiences worldwide. His projects focus on innovative digital marketing ideas with strategic thought and accuracy.

Advanced Data Science AI