Blog

  • Data Analysis

    Data analysis is essential for modern research and business. It offers information to support innovation, strategy development, and decision-making. Computer languages like Python and R which are known for their vast libraries and statistical capabilities, have historically been linked to data analysis.

    However JavaScript is best known for web development and is gradually gaining popularity in data analysis. This chapter covers the use of JavaScript in data analysis, concentrating on its capabilities, tools and conditions where it can be used effectively.

    Introduction to Data Analysis with JS

    JavaScript’s importance in data analysis has grown considerably as a result of the development of advanced tools and frameworks for statistical calculation, data visualization and large dataset management.

    Whether you are focusing on client-side analytics, server-side computations or data visualization for web apps, JavaScript provides excellent options.

    Data Analysis Libraries in JS

    Below are some libraries listed used to data analysis in JavaScript −

    D3.js (Data-Driven Documents)

    D3.js is an advanced framework for creating rich, interactive data visualizations based on web standards. It allows developers to link any kind of data to the Document Object Model (DOM) and perform data-driven transformations on the document.

    D3.js’ flexibility and large capacity make it a popular choice for developing custom visualizations that properly show complex datasets.

    Chart.js

    Chart.js is a simple and versatile framework for making responsive charts. It supports a variety of chart formats, like line, bar, radar, doughnut and pie charts, which makes it suitable for a wide range of data visualization applications.

    Chart.js’s simplicity of use and compatibility with modern web frameworks make it a popular choice among developers wanting to quickly add interactive charts to their apps.

    Plotly.js

    Plotly.js is a high-level, declarative charting framework based on D3.js and stack.gl. It supports a variety of chart styles and provides major customization possibilities.

    Plotly.js is well-known for its ability to generate scientific and financial charts, as well as its support for 3D visualization and geographic mapping.

    Node.js and Express

    Node.js’ asynchronous, event-driven architecture makes it perfect for data-intensive applications. When combined with Express, a basic and versatile Node.js web application framework, it can be an effective tool for developing APIs and data processing pipelines.

    Node.js is able to handle massive amounts of data, making it an excellent choice for back-end data processing.

    TensorFlow.js

    TensorFlow.js is a library that allows you to create and train machine learning models directly in the browser or with Node.

    It extends TensorFlow’s capability to JavaScript which is allowing developers to build and run machine learning models without moving to a new programming environment.

    This allows for the easy integration of powerful data analysis and machine learning capabilities into JavaScript applications.

    Strengths of JavaScript in Data Analysis

    Here are some of the strengths listed below of JavaScript in data analysis −

    Ubiquity and Accessibility

    One of the most significant advantages of JavaScript is that it is used widely.

    JavaScript is the foundation of web development and all modern browsers support it, making it very easy to use.

    Because of its widespread availability, JavaScript code can be executed by anybody with a web browser, making it an excellent choice for interactive and web-based data visualization and analysis applications.

    Integration with Web Technologies

    JavaScript’s easy integration with HTML, CSS, and other web technologies allows the creation of complex, dynamic data visualizations.

    This connection is used by libraries like D3.js, Chart.js, and Plotly.js to generate dynamic charts and graphs that can be included directly in web pages.

    This feature is extremely useful in displaying data analysis results in a readable and accessible format.

    Event-Driven Programming

    JavaScript is a great tool for working with real-time data because of its event-driven nature. This is particularly helpful for tasks that involve ongoing data streams, like tracking social media trends, keeping an eye on financial markets, or analyzing Internet of Things devices.

    JavaScript can effectively manage and visualize live data and providing timely insights and allowing quick decisions.

    How to Find the Average with JavaScript?

    Finding the highest and lowest values in a dataset is an important step in data analysis. JavaScript has a variety of methods for accomplishing this, which are very helpful when manipulating and analyzing data. In JavaScript the average of a collection of integers is calculated by adding all of the values and dividing by their count.

    Data Analysis Context

    Finding the maximum and minimum values is usually considered one of the first steps in analyzing a dataset. It helps in understanding the range and distribution of data, identifying outliers and explaining key statistical concepts.

    Practical Applications

    Here are some practical applications listed below −

    • Descriptive statistics analyzes data by determining the range (difference between maximum and minimum values).
    • Data cleaning consists of detecting outliers that must be addressed.
    • Data visualization needs changing sizes and limits on charts and graphs to correctly represent data.

    Example

    Here is the findAverage function with a different example −

    functionfindAverage(arr){let sum = arr.reduce((acc, val)=> acc + val,0);return sum / arr.length;}// Driver Codelet numbers =[12,18,24,30,36];let average =findAverage(numbers);
    console.log("Average:", average);

    Output

    This will produce the below result −

    Average: 24
    

    Find the Maximum and Minimum with JavaScript

    To find the maximum and minimum values in an array in JavaScript, use the Math.max() and Math.min() functions, as well as the spread operator (…) for arrays.

    Data Analysis Context for Maximum and Minimum Values

    In data analysis finding the maximum and minimum values in a dataset is significant for a variety of reasons −

    • Range Calculation: The range represents the difference between the maximum and least values. It provides a basic measure of the distribution of the data.For the dataset [5, 12, 8, 130, 44] the range is 130 – 5 = 125.
    • Identifying Outliers: Outliers are values that differ completely from the remainder of the dataset. Knowing the maximum and minimum values helps you identify these anomalies.In the dataset [5, 12, 8, 130, 44] 130 is possibly an outlier.
    • Setting Data Boundaries: When visualizing data having the minimum and maximum values helps in determining the scale of axes for charts and graphs.For example, in a bar chart, setting the y-axis from 0 to 130 guarantees that all data points are visible.
    • Data Summary and Descriptive Statistics: Maximum and minimum values are important for summary statistics, as they provide a fast snapshot of the dataset’s distribution.Descriptive statistics like mean, median and mode are often added by minimum and maximum values to provide context.

    Example

    Below example shows the implementation of the above explanation.

    functionfindMax(arr){return Math.max(...arr);}functionfindMin(arr){return Math.min(...arr);}// Examplelet numbers =[42,7,29,83,56];let max =findMax(numbers);let min =findMin(numbers); 
    console.log("Maximum:", max);
    console.log("Minimum:", min);

    Output

    This will generate the below output −

    Maximum: 83
    Minimum: 7
    

    Summary

    JavaScript has grown into a powerful language for data analysis, with modules and tools that help everything from basic statistical computations to complex machine learning tasks and interactive data visualizations.

  • CORS Handling

    Cross-Origin Resource Sharing (CORS) is a browser-level security feature that, by default, blocks queries across different origins, like a front-end client querying a back-end server hosted on a separate origin or domain.

    We can use a variety of strategies to avoid or enable cross-origin queries. In this chapter, we will use code examples to demonstrate how to handle CORS in JavaScript.

    What Is CORS?

    CORS is a security feature in web browsers which is used to prevent malicious sites from making unwanted requests to other domains. It maintains the same-origin policy, which prevents web pages from sending requests to domains other than those that served the page. CORS enables servers to specify who can access their resources.

    Importance of CORS

    CORS is important for security, however it might be difficult during web development and API use. Developers deal with problems while trying to access resources from many domains. Let us examine these common issues and their solutions.

    CORS Handling using Express server

    In this method, we will develop and use NodeJS and ExpressJS servers to handle CORS requests. To accept requests from any origin, we can add the “Access-Control-Allow-Origin” header to each response object header.

    Example

    First you need to install the necessary packages for the application by using the below steps −

    npm init -y
    npm i express
    

    Create the index.js file: Create the index.js file and set up the express server. Allow the “Access-Control-Allow-Origin” response header to be delivered for all requests to the same file.

    const express =require('express');const server =express();
    
    server.use((request, response, proceed)=>{
       response.header('Access-Control-Allow-Origin','*');
       response.header('Access-Control-Allow-Methods','GET, POST, PUT, DELETE');
       response.header('Access-Control-Allow-Headers','Origin, X-Requested-With, Content-Type, Accept');proceed();});
    
    server.get('/info',(request, response)=>{
       response.json({country:'India', currencyCode:'INR'});});
    server.listen(3000,()=>{
       console.log('Application is live on port 3000');});

    Run the express API server: Now you have to start the server with the help of the below command.

    npm start
    

    Create a Vanilla JS Application: Now you have to create a vanilla JavaScript application for consuming the above API server endpoint. For this you have to run the following commands in the terminal to create a basic structure for creating our JS application.

    mkdir cors-test
    cd cors-test
    touch index.html 
    

    Now, change the project structure’s index.html file to request data from the express API server and show it in the user interface.

    The index.html file is as follows −

    <!DOCTYPE html><html lang="en"><body><h1>Data from Server</h1><div id="infoDisplay"></div><script>
    
         document.addEventListener('DOMContentLoaded', () =&gt; {
            const infoContainer = document.getElementById('infoDisplay');
            fetch('http://localhost:3000/info').then(serverResponse =&gt; serverResponse.json()).then(info =&gt; {
               const {
                  country,
                  currencyCode
               } = info;
               infoContainer.innerHTML = `
                     
      	&lt;p&gt;Country: ${country}&lt;/p&gt;&lt;p&gt;Currency Code: ${currencyCode}&lt;/p&gt;
                  `;
            }).catch(fetchError =&gt; {
               console.warn('Failed to retrieve data:', fetchError);
               infoContainer.innerHTML = ' &lt; p &gt; Error retrieving data.Please
               try again later. &lt; /p&gt;';
            });
         });
      &lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Run the Vanilla JS Application: Now you can open the index.html file you have created above and see the output in the browser.

    Output

    This will generate the below result −

    CORS Example

    Common CORS Issues

    Here are some of the common issues are listed for your reference −

    Unauthorized Access Blocked by CORS

    One of the most common CORS issue is getting the error 'Access to XMLHttpRequest at 'URL' from origin 'Origin' has been blocked by CORS policy' in the browser console.

    To handle this problem you need to setup your server to provide the required CORS headers to enable access from the requesting origin.

    Example using Node.js and Express.js

    Following is the example using node.js and express.js −

    const express =require('express');const server =express();// Enable CORS for a specific origin
    server.use((request, response, proceed)=>{
       response.setHeader('Access-Control-Allow-Origin','https://example.com');
       response.setHeader('Access-Control-Allow-Methods','GET, POST, PUT, DELETE');
       response.setHeader('Access-Control-Allow-Headers','Content-Type, Authorization');// If cookies are needed
       response.setHeader('Access-Control-Allow-Credentials','true');proceed();});// Your API routes
    server.get('/api/info',(request, response)=>{// Your response logic
       response.json({ details:'Information from the server'});});
    
    server.listen(3000,()=>{
       console.log('Application active on port 3000');});

    In this example, we enabled CORS for a given origin (https://example.com) by giving the headers. This enables requests from https://example.com to access server resources.

    Missing CORS Headers

    Sometimes the server fails to include the required CORS headers when it responses, leading the browser to block the request.

    Make that your server contains the necessary CORS headers in its answers to allow cross-origin queries.

    Example using Node.js and Express.js

    Here is the example using node.js and express.js −

    const express =require('express');const server =express();// Add CORS headers to all responses
    server.use((request, response, proceed)=>{
       response.setHeader('Access-Control-Allow-Origin','*'); 
       response.setHeader('Access-Control-Allow-Methods','GET, POST, PUT, DELETE');
       response.setHeader('Access-Control-Allow-Headers','Content-Type, Authorization');// If cookies are needed
       response.setHeader('Access-Control-Allow-Credentials','true');proceed();});// Your API routes
    server.get('/api/info',(request, response)=>{// Your response logic
       response.json({ info:'Information from the server'});});
    
    server.listen(3000,()=>{
       console.log('Application is now active on port 3000');});

    In this example, CORS headers are added to all responses using middle-ware, enabling requests from any origin. But for security reasons, acceptable origins must be limited in a production environment.

  • Code Testing with Jest

    You can increase your application’s reliability and maintainability by testing your code to find errors earlier using Jest. Jest is a popular choice for JavaScript testing, particularly for applications made using Node.js, React, Angular, and Vue.js. Let us look at Jest’s features and how to use them.

    What is Jest?

    The Jest testing framework, created by Facebook, focuses efficiency and adaptability. Jest easily integrates with JavaScript and TypeScript applications and supports popular libraries and frameworks like React. Among its main features are integrated mocking support, zero configuration and snapshot testing.

    Features of Jest

    Here are some features you need to know before working with Jest −

    • Zero Config: To start creating and delivering tests, virtually no configuration is needed. But the test suite can also be provided using a configuration file.
    • Snapshots: Snapshot testing can also be enabled using Jest. In simple terms, the saved snapshot and the snapshots are compared to see whether there is any matching functionality.
    • Isolated testing: To reduce execution time, Jest tests are executed in parallel.
    • Mocking Support: Jest makes it easy to create fictitious functions so you can test how your code interacts with other components.

    Setting Up Jest

    For using Jest you have to first install it in your project. Use the below steps −

    1. Initialize a Project: So you have to open a terminal and navigate to your project folder then run the below command −

    npm init -y
    

    2. Install Jest: Then you have to run the below command −

    npm install --save-dev jest
    

    3. Add Jest to Your Scripts: Locate the package.json file and in this file you have to add the following line −

    "scripts":{"test":"jest"}

    Now you can write your first test for your JavaScript code.

    Example 1

    Here is the simple and basic test that checks if the function sum returns the proper result.

    // sum.jsfunctionsum(a, b){return a + b;}
    module.exports = sum;

    Test File

    Here is the test file code −

    // sum.test.jsconst sum =require('./sum');test('adds 1 + 2 to equal 3',()=>{expect(sum(1,2)).toBe(3);});

    Run the above test code by the following command −

    npm test
    

    In this test – expect(sum(1, 2)).toBe(3); checks that sum(1, 2) returns 3.

    Example 2

    Jest handles asynchronous testing easily. Let’s create an asynchronous function and test it.

    // fetchData.jsasyncfunctionfetchData(){return'freeCodeCamp';}
    module.exports = fetchData;

    Test File

    Here is the test file code −

    // fetchData.test.jsconst fetchData =require('./fetchData');test('the data is freeCodeCamp',async()=>{const data =awaitfetchData();expect(data).toBe('freeCodeCamp');});

    Here Jest executes expect after fetchData() is complete.

    Example 3

    Mock functions let you test and model code interactions without needing the actual function. This is how to create a simple mock function.

    const myMockFunction = jest.fn(x=> x +42);test('mock function test',()=>{expect(myMockFunction(0)).toBe(42);});

    In this test, jest.fn() is used to generate a mock function that adds 42 to any input value. This test confirms that when myMockFunction(0) is invoked, 42 is returned.

  • Circular Reference Error

    When an object creates a direct or indirect reference to itself, it is known as circular referencing. It makes the loop closed. JavaScript has the same circular referencing issue as other programming languages. A few errors of JavaScript circular referencing modes will be discussed in this chapter.

    What is a Circular Reference in JS?

    In JavaScript, a circular reference happens when two or more objects make reference to one another in a way that starts a loop. You have a circular reference, for example- if object A refers to object B and object B in turn refers back to object A.

    Example

    Here is the basic example of circular reference in JavaScript −

    let person ={};let friend ={};// Making a circular reference
    person.bestFriend = friend;
    friend.bestFriend = person;

    This creates a loop in which person refers a friend, who in turn mentions the person.

    Problems With Circular References

    It is preferable to organize data without cross-references between objects in order to prevent circular references.

    • Memory leaks: These happen when JavaScript’s garbage collection refuses to remove objects with circular references resulting in memory that is not released.
    • Stringify errors in JSON: Errors happen when circular references are tried to be converted to JSON, for example, by using JSON.stringify(). Because this method cannot support circular structures, an error will be produced.
    let obj ={};
    obj.self = obj;// Throws "TypeError: Converting circular structure to JSON"JSON.stringify(obj);

    How to Fix Circular References

    A few standard methods can be used to correct circular references. These include using particular libraries that can handle circular structures, removing references prior to converting to JSON and rearranging data to prevent loops.

    Remove Circular References

    Find the location of the circular reference and remove it if it is not needed.

    let obj1 ={};// Avoid circular reference by not pointing obj1 back to obj2let obj2 ={ obj1: obj1 };
    
    console.log(JSON.stringify(obj2));

    Output

    This will generate the below result −

    {"obj1":{}}
    

    Use a Custom toJSON Method

    If you want to stringify an object with circular references you can create a custom toJSON function to ignore them.

    let obj ={};
    obj.self = obj;
    
    obj.toJSON=function(){let copy ={...this};// Remove circular referencedelete copy.self;return copy;};// This will now work without errors
    console.log(JSON.stringify(obj));

    Output

    This will lead to the below output −

    {}
    

    Use a Library

    Some libraries like flatted or circular-json can handle circular references automatically. Use the package instead of JSON.stringify() after installing it.

    // Using circular-json const CircularJSON =require('circular-json');let obj ={};
    obj.self = obj;let jsonString = CircularJSON.stringify(obj);// Converts circular structure to JSON without error
    console.log(jsonString);

    Output

    This will produce the following outcome −

    {"self":"~"}
  • Bubble Sort Algorithm

    The stages of Bubble Sort are covered in this chapter, which includes a JavaScript implementation. The word ‘sort’ refers to the process of rearranging the elements in ascending order.

    Bubble Sort Algorithm

    Bubble sort is a great starting point for those who are new to sorting. Since its algorithm looks similar how our brains usually think about sorting by comparison it is among the most simple sorting techniques.

    When using Bubble Sort the adjacent elements in the array are compared and if the first element is greater than the second the places are switched. In this way the highest value “bubbles” will come at the top.

    At the end of each iteration, the parts nearest the right are frequently in the correct order. The process is repeated until each element is in the right place.

    Now let us see what exactly bubble sort does −

    • Starting with the first element in the array and compare it to the current element.
    • If the array’s current element is bigger than the next element, switch them.
    • If the current element is less than it and just move on to the next one.
    • Continue from Step 1 again.

    Demonstration of Bubble Sort

    Here are the iterations of the bubble sort −

    Iteration 1:[8,3,7,1,5]->[3,8,7,1,5]->[3,7,8,1,5]->[3,7,1,8,5]->[3,7,1,5,8]
    Iteration 2:[3,7,1,5,8]->[3,7,1,5,8]->[3,1,7,5,8]->[3,1,5,7,8]
    Iteration 3:[3,1,5,7,8]->[1,3,5,7,8]->[1,3,5,7,8]
    Iteration 4:[1,3,5,7,8]->[1,3,5,7,8]
    Final Sorted List:[1,3,5,7,8]

    Implementing Bubble Sort in JavaScript

    The input of the bubbleSort function is the array arr. It uses two loops. The outer loop iterates over each element up to n-1 times, where n is the array’s length. The inner loop compares and switches adjacent elements if they are out of order.

    A swapped flag is used to optimize the sort. If the array is already sorted and no swaps are made during a pass so we can end the loop early.

    functionbubbleSort(arr){let n = arr.length;let swapped;for(let i =0; i < n -1; i++){
    
      swapped =false;for(let j =0; j &lt; n -1- i; j++){// Compare adjacent elementsif(arr[j]&gt; arr[j +1]){// Swap if they are in the wrong orderlet temp = arr[j];
            arr[j]= arr[j +1];
            arr[j +1]= temp;
                
            swapped =true;}}// If no elements were swapped, the array is already sortedif(!swapped)break;}return arr;}// Example let arr =[8,3,7,1,5];
    console.log("Sorted array:",bubbleSort(arr));

    Output

    This will generate the below result after sorting the elements −

    Sorted array: [ 1, 3, 5, 7, 8 ]
    

    Another Way to Implement Bubble Sort

    Here is another way to create Bubble Sort in JavaScript using a slightly different structure −

    functionbubbleSort(arr){let n = arr.length;for(let i = n -1; i >0; i--){for(let j =0; j < i; j++){// Compare adjacent elementsif(arr[j]> arr[j +1]){// Swap if they are in the wrong order// Using destructuring for swapping[arr[j], arr[j +1]]=[arr[j +1], arr[j]];}}}return arr;}// Examplelet arr =[8,3,7,1,5];
    console.log("Sorted array:",bubbleSort(arr));

    Output

    This will produce the following result −

    Sorted array: [ 1, 3, 5, 7, 8 ]
    

    Complexities

    In the worst case scenario and average case time complexity the array is in reverse order so in this situation it has O(n2) time complexity.

    And in the optimal time complexity and in the ideal situation the array’s time complexity is O(n) and it is already sorted. The auxiliary space is O(1).

  • DOM DOMTokenList

    DOMTokenList

    The DOMTokenList is an interface in DOM (Document Object Model) which represents a set of space-separated tokens (classes). Generally, it is used for managing the classes in HTML elements.

    It may look like an array, but it is not. Similar to an array, you can loop through a DOMTokenList and access its tokens by index. However, you cannot use array methods such as push(), pop(), or join() on a DOMTokenList.

    You can retrieve individual tokens using their numerical index in the DOMTokenList. For example, element.classList[0] would give you the first-class name of an element.

    The following diagram clearly explains the JavaScript DOMTokenList interface. As you can see a DOMTokenList can contain a list of values (tokens) −

    DOMTokenList

    The following interactive example will use 2-3 important methods as button functionalities. Whenever the user interacts with the page, the respective method will be performed −

    Click on the below buttons to see the changes…..

    TutorialspointAddRemoveToggle

    Below is the explanation of the example above:

    • If you click the “Add” button, the ‘DOMTokenList’ add() method will be called, and the class ‘tp’ will be added to “tutorials”.
    • If you click the “Remove” button, the remove() method will be called to remove the added class.
    • If you click the “Toggle” button, the toggle() method will be called, which will add and remove the class alternately.

    JavaScript DOMTokenList Methods

    The DOMTokenList is an interface that represents a set of space-separated tokens. These tokens can be seen in properties such as classList, HTMLLinkElement, relList, and many others.

    Following is a list of methods provided by the JavaScript DOMTokenList −

    Sr.NoMethod & Description
    1add()This method adds one or more tokens specified in the parameter to the DOMTokenList.
    2contains()This method checks whether the list contains the specified token, and returns a boolean value accordingly.
    3entries()This method returns an iterator that is allowing to go through all the key/value pairs.
    4forEach()This method calls the callback function mentioned in the parameter once for each value pair in the list in the order of their insertion.
    5item()This method returns a token from the DOMTokenList specified by the index in the parameter.
    6keys()This method returns an iterator which allows you to go through all the keys contained in the token list.
    7remove()This method removes one or more tokens specified in the parameter to the DOMTokenList.
    8replace()This method replaces the existing token in DomTokenList with a new token specified in the parameter.
    9supports()This method checks whether the token specified in the parameter is supported in DOMTokenList.
    10toggle()This method dynamically adds or removes a token or class from an element class attribute.
    11values()This method returns an iterator allowing us to go through all values contained in the token list.

    JavaScript DOMTokenList Properties

    Following is a list of properties provided by the JavaScript DOMTokenList −

    Sr.NoProperties & Description
    1lengthThis method returns the number of tokens in a token list.
    2valueThis method returns the DOMTokenList serialized as a string.

    Example 1: Retrieving the length of the DOMTokenList.

    The following example demonstrates the usage of the DOMTokenList length property −

    <!DOCTYPE html><html lang="en"><body><p>DOMTokenList Example</p><div id="myList"class="tp1 tp2 tp3">I'm inside div.</div><span id="result"></span><script>let list = document.getElementById("myList").classList;
    
        document.getElementById('result').innerHTML ="DOMTokenList length (number of classes) is : "+ list.length;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    The above program returns the length of the DOMTokenList (or number of classes) −

  • DOM NodeList

    DOM NodeList

    The NodeLists are similar to an array or HTMLCollection containing the HTML elements. However, it is not the same as the array or HTML collection.

    All modern browsers return the node list when you use querySelectorAll() method and childNodes properties. You can traverse the NodeList as an array but can’t use other array methods like map(), filter(), etc, with node lists.

    The following diagram clearly explains the JavaScript NodeList interface. As you can see, an HTML code snippet contains all types of nodes:

    DOM NodeList

    JavaScript DOM NodeList Methods

    Following is a list of methods provided by the JavaScript NodeList −

    Sr.NoMethod & Description
    1entries()This method retrieves an iterator, that allows us to iterate through all the key/value pairs in the object.
    2forEach()This method calls the callback function mentioned in the parameter once for each value pair in the list in the order of their insertion.
    3item()This method retrieves a node from the NodeList specified by the index in the parameter.
    4keys()This method retrieves an iterator that allows us to go through all the keys contained in the NodeList.

    JavaScript DOM NodeList Properties

    Following is a list of properties provided by the JavaScript NodeList −

    Sr.NoProperties & Description
    1lengthThis method returns the number of items in the NodeList.

    Example 1: Retrieving a specific element from a NodeList.

    The following example demonstrates the usage of the JavaScript DOM NodeList −

    <!DOCTYPE html><html lang="en"><head><title>JavaScript DOM NodeList</title></head><body><div><p>This is first paragraph.</p><p>This is second paragraph.</p><p>This is third paragraph.</p><p>This is fourth paragraph.</p></div><script>
    
        let myNodeList = document.querySelectorAll('p');
        //you can access the node list by index
        //access the third node list
        alert("This is third P: " + myNodeList[2].innerHTML);
    &lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    The program uses "querySelectorAll()" to select all "p" elements as a NodeList. By passing the index value as "2", it alerts the third "p" element in the document −

    Example 2: Adding Style to NodeList (<div>) element.

    In this example, we use the "getElementsByTagName('div')" method to select all "<div>" elements and return them as a NodeList. Now, we can apply styles to these elements −

    <!DOCTYPE html><html lang="en"><head><title>JavaScript DOM NodeList</title><style>
    
        button{
            padding: 8px 20px;
            margin: 20px 0px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
        }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;p&gt;Click the button below to add style to all "div" elements.&lt;/p&gt;&lt;div&gt;Div 1&lt;/div&gt;&lt;div&gt;Div 2&lt;/div&gt;&lt;div&gt;Div 3&lt;/div&gt;&lt;div&gt;Div 4&lt;/div&gt;&lt;div&gt;Div 5&lt;/div&gt;&lt;button id="btn"&gt;Add style&lt;/button&gt;&lt;script&gt;
    document.getElementById('btn').addEventListener("click", ()=>{
      //using getElementsByTagName() method
      let myNodeList = document.getElementsByTagName('div');
      //using length property
      for(let i = 0; i&lt;myNodeList.length; i++){
          myNodeList[i].style.color = 'white';
          myNodeList[i].style.padding = "10px";
          myNodeList[i].style.margin = "5px";
          myNodeList[i].style.border = "1px solid black";
          myNodeList[i].style.backgroundColor = "green";
      }
    });
    &lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    On executing the above program, a button is displayed. When clicked, it applies a new style to all "div" elements −

    Example 3: Using the forEach() method to traverse the NodeList elements.

    In this example, we have four <p> elements. We use "querySelectorAll('.lang')" to select all elements with the class "lang" and traverse the NodeList using "forEach()" method −

    <DOCTYPE html><html><body><p class="lang"> English </p><p class="lang"> German </p><p class="lang"> Arabic </p><p class="lang"> Hindi </p><br><div id ="output"></div><script>const output = document.getElementById('output');
    
      output.innerHTML +="All languages are: &lt;br&gt;";const langs = document.querySelectorAll('.lang');
      langs.forEach((language)=&gt;{
         output.innerHTML += language.innerHTML +'&lt;br&gt;';})&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    After execution, the above program displays all "p" elements having the the class name equal to "lang" −

    Example 4: Retrieving the length of the NodeList.

    In the below code, we have used the 'length' property of the NodeList to count the number of nodes in the NodeList.

    <DOCTYPE html><html><body><div class="fruit"> Apple </div><div class="fruit"> Orange </div><div class="fruit"> Banana </div><div class="fruit"> Mango </div><div id ="output">Total number of fruits are :</div><script>const fruits = document.querySelectorAll('.fruit');
    
      document.getElementById('output').innerHTML += fruits.length;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    The above program returns the length of NodeList −

    Difference between HTMLCollection and NodeList

    The HTMLCollection and NodeList look similar, but there is a minor difference between them, which we have explained in the table below −

    FeatureHTMLCollectionNodeList
    Return byGenerally, getElementByClassName(), getElementByTagName methods, and children properties return the HTML collection.Generally, the querySelectorAll() method and childNodes property return the Node list.
    Array methodsIt supports limited array methods.It also supports limited array methods like forEach().
    Live collectionSome browser supports live collection with HTML collection.It updates if you update the DOM element.
  • DOM Collections

    DOM Collections

    The DOM (Document Object Model) collections are a way to group together related HTML elements. They are read-only and can be accessed using the properties of DOM objects such as the document object or a DOM node.

    There are many different types of DOM collections, including:

    • The HTMLCollection object is an array-like list (collection) of HTML elements.
    • The NodeList object is a list (collection) of nodes extracted from a document.
    • The Form element collection in HTML DOM is used to set or return the collection of all <input> elements inside a form element.
    • The HTML DOM forms collection is used for returning all the form elements that are present inside the HTML document as a collection.

    DOM collections can be used to perform a variety of tasks, such as:

    • Traversing the DOM
    • Adding, removing, or modifying elements
    • Changing the style or content of elements
    • Responding to user events

    This tutorial provides basic understanding of DOM collections, particularly HTMLCollection object. The other type of DOM collections are discussed in next chapters.

    The HTMLCollection Object

    An HTMLCollection object is an array-like data structure of HTML elements. When you use the getElementByTagName()method to access DOM elements, it returns an HTMLCollection object.

    It is the same as an array but not an array. You can traverse the HTML collection and access each HTML element through the index, but you can use the pop(), push(), etc. methods with HTML collection.

    The methods and properties given below return the HTML collection.

    • getElementByTagName() method
    • getElementByClassname() method
    • children property

    Properties and Methods of DOM HTMLCollection Object

    Here, we have listed the properties and methods that can be used with HTML collections.

    Method / PropertyDescription
    lengthTo get a count of HTML elements in the collection.
    item()To get elements from the specific index.
    namedItem()To get the HTML element using its id from the given collection.

    Example: Traversing the Collection Elements

    In the below code, we have added the list of numbers.

    In JavaScript, we access all <li> elements using the getElementByTagName() method, which returns the HTML collection.

    After that, we use the for…of loop to traverse each HTML element. The collection contains each HTML element in the object format. We used the innnerHTML property with each element of the collection to get its HTML and print it on the web page.

    <DOCTYPE html><html><body><ul><li> One </li><li> Two </li><li> Three </li></ul><div id ="output"></div><script>const output = document.getElementById('output');let lists = document.getElementsByTagName('li');for(let list of lists){
    
         output.innerHTML +="inner HTML - "+ list.innerHTML +"&lt;br&gt;";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Example: Getting the length of the collection

    In the below code, we used the 'length' property of the collection to get the number of elements in the collection.

    <DOCTYPE html><html><body><div class="text"> JavaScript </div><div class="text">HTML</div><div class="text">CSS</div><div class="text">CPP</div><div id ="output">The length of the collection is:</div><script>const divs = document.getElementsByClassName('text');
    
      document.getElementById('output').innerHTML +=" "+ divs.length;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Example: Using the namedItem method with collection

    In the below code, we access all <div> elements using the getElementByClassName() method, returning the collection of <div> elements.

    After that, we used the namedItem() method to access the <div> element having id equal to 'JavaScript'.

    <DOCTYPE html><html><body><div class="text" id ="JavaScript"> JavaScript </div><div class="text" id ="PHP">PHP</div><div class="text" id ="Python"> Python </div><div class="text" id ="Java"> Java </div><div id ="output">The Element having id equal to JavaScript is:</div><script>const output = document.getElementById('output');const langs = document.getElementsByClassName('text');
    
      output.innerHTML += langs.namedItem('JavaScript').innerHTML;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Collections of document Object and DOM Elements

    The document object contains some built-in collection to get the elements from the document.

    In the below table, we have listed all collections which can be accessed using the document object.

    Collection NameDescription
    document.linksTo get all <a> elements from the document.
    document.formsTo get all <form> elements from the document.
    document.imagesTo get all <img> elements from the document.
    document.scriptsTo get all <script> elements from the document.
    document.styleSheetsTo get all the document's <link> and <style> elements.
    Element.childrenTo get a collection of all children of the particular HTML element.
    element.attributesTo get the collection of all attributes of the given element.
    element.optionsTo get all <options> elements from the document.
    element.classListTo get a collection of class names of a particular DOM element.
  • DOM Navigation

    In JavaScript, with HTML DOM we can navigate the tree nodes using the relationship between the nodes. Each HTML element is represented as a node in the DOM tree. The HTML document object is represented as root node. There are different types of nodes such as root node, parentchild and sibling nodes. The relationship between these nodes help to navigate the DOM tree.

    What are DOM Nodes?

    When a webpage gets loaded in the browser, it creates a document object. The ‘document’ object is the root of the web page, and you can access other HTML nodes of the web page.

    In the HTML DOM, everything is a node.

    • The ‘document’ is a parent node of each node.
    • Each HTML element is a node.
    • The text inside the HTML element is a node.
    • All comments inside the HTML are node is the node.

    You can access all nodes of the HTML DOM.

    Relationship between HTML DOM Nodes

    In the HTML DOM, each node has a relationship with other nodes. Each node is present in the hierarchical structure in the DOM tree.

    Here are the terms which we will use in this chapter.

    • Root node − The document node is a root node.
    • Parent node − Each node has a single parent node. The root node doesn’t have any parent node.
    • Child node − Each node can have multiple and nested childrenders.
    • Sibling node − The sibling nodes are at the same level, having the same parent node.

    Let’s understand the relationship between nodes in the below example.

    Example

    <html><head><title> JavaScrip -DOM Navigation </title></head><body><div><h3> Hi Users!</h3><p> Hello World!</p></div></body></html>

    In the above program,

    • <html> is a root node, and it doesn’t have a parent node.
    • The <html> node contains two child elements: <body> and <head>.
    • The <head> element contains the single child element: <title>.
    • The <title> node contains the single <text> node.
    • The <body> element contains the single child node: <div>.
    • The <div> node contains two child nodes: <h2> and <p>.
    • <h2> and <p> are siblings.
    • The parent of the <h2> and <p> is <div> node.
    • The parent of the <div> node is <body> node.

    Navigating Between Nodes Using JavaScript

    Navigating between nodes means finding the parent, child, sibling, etc. element of a particular element in the DOM tree.

    You can use the below methods and properties to navigate between nodes in the DOM tree.

    PropertyDescription
    firstChildTo get the first child of the particular node. It can also return the text, comment, etc.
    firstElementChildTo get the first child element. For example, <p>, <div>, <img>, etc.
    lastChildTo get the last child of the particular node. It can also return the text, comment, etc.
    lastElementChildTo get the last child element.
    childNodesTo get the node list of all children of the particular element.
    childrenTo get the HTML collection of all children of the particular element.
    parentNodeTo get the parent node of the HTML element.
    parentElementTo get the parent element node of the HTML element.
    nextSiblingTo get the next node from the same level having the same parent node.
    nextElementSiblingTo get the next element node from the same level having the same parent node.
    previousSiblingTo get the previous node from the same level having the same parent node.
    previousElementSiblingTo get the previous element node from the same level having the same parent node.

    Below, we will use each method to navigate through the DOM elements.

    Accessing the First Child Element

    You can access the particular child element using the firstChild or firstElementChild property.

    Syntax

    Follow the syntax below to use the ‘firstChild’ and ‘firstElementChild’ properties to access the first child element.

    element.firstChild;
    element.firstChildElement;

    Example

    In the below code, <div> element contains the text followed by three <p> elements.

    When we use the ‘firstChild’ property, it returns the text node containing the ‘Numbers’ text, and when we use the ‘firstChildElement’ property, it returns the first

    element.

    <!DOCTYPE html><html><body><div id ="num">Numbers
    
    &lt;p&gt; One &lt;/p&gt;&lt;p&gt; Two &lt;/p&gt;&lt;p&gt; Three &lt;/p&gt;&lt;/div&gt;&lt;div id ="demo"&gt;&lt;/div&gt;&lt;script&gt;const output = document.getElementById('demo');const numbers = document.getElementById('num');// Using the firstChild property
    output.innerHTML +="numbers.firstChild: "+ 
    numbers.firstChild.textContent.trim()+"&lt;br&gt;";// Using the firstElementChild property
    output.innerHTML +="numbers.firstElementChild: "+ numbers.firstElementChild.textContent +"&lt;br&gt;";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Accessing the Last Child Element

    You can use the lastChild or lastChildElement properties to access the last child of the particular HTML node.

    Syntax

    Follow the syntax below to use the 'lastChild' and 'laststElementChild' properties to access the las=st child element.

    element.lastChild;
    element.lastChildElement;

    Example

    In the below code, we have defined the <div> element containing 3 <p> elements containing the name of the programming languages.

    In the output, you can see that the lastElementChild property returns the last <p> element, and the lastChild property returns the text node of the div element.

    <!DOCTYPE html><html><body><div id ="lang"><p> Java </p><p> JavaScript </p><p>HTML</p>
    
    Programming Languages
    </div><div id ="demo"></div><script>const output = document.getElementById('demo');const langs = document.getElementById('lang');// Using the lastChild property
    output.innerHTML +="langs.lastChild: "+ langs.lastChild.textContent.trim()+"&lt;br&gt;";// Using the lastElementChild property
    output.innerHTML +="langs.lastElementChild: "+ langs.lastElementChild.textContent +"&lt;br&gt;";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Accessing all children of HTML Element

    You can use the childNodes property to access the node list of all children elements or the children property to access the HTML collection of all children.

    Syntax

    Follow the syntax below to access all children elements of the DOM element.

    element.children;
    element.childNodes;

    Example

    In the below code, we use the childNodes property to access all child nodes of the <div> element.

    In the output, you can see that it also returns the text nodes with undefined text as it contains the text nodes after and before each HTML element node.

    <!DOCTYPE html><html><body><div id ="lang"><p> Java </p><p> JavaScript </p><p>HTML</p>
    
      programming Languages
    </div><div id ="output"></div><script>let output = document.getElementById('output');let langs = document.getElementById('lang');
      output.innerHTML +="All children of the div element are - "+"&lt;br&gt;";let allChild = langs.childNodes;for(let i =0; i &lt; allChild.length; i++){
         output.innerHTML += allChild[i].nodeName +" "+ allChild[i].innerHTML +"&lt;br&gt;";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Accessing the Parent Node of HTML Element

    You can use the parentNode property to access the parent node of the particular HTML node.

    Syntax

    Follow the syntax below to use the parentNode property.

    element.parentNode;

    Example

    In the below code, we access the <li> element having d equal to 'blue' in JavaScript. After that, we use the parentNode property to access the parent node.

    It returns the 'UL' node, which we can observe in the output.

    <!DOCTYPE html><html><body><ul id ="color"><li id ="blue"> Blue </li><li> Pink </li><li> Red </li></ul><div id ="output">The child node of the color list is:</div><script>const blue = document.getElementById('blue');
      document.getElementById('output').innerHTML += blue.parentNode.nodeName;</script></body></html>

    Accessing the Next Sibling Node

    The nextSibling property is used to access the next sibling.

    Syntax

    Follow the syntax below to use the nextSibling property.

    element.nextSibling
    

    Example

    In the below code, we have access to the <li> element with an id equal to 'apple', and access to the next sibling node using the nextSibling property. It returns the <li> node having the id equal to 'banana'.

    <!DOCTYPE html><html><body><ul id ="fruit"><li id ="apple"> Apple </li><li id ="banana"> Banana </li><li id ="watermealon"> Watermealon </li></ul><div id ="output">The next sibling node of the apple node is:</div><script>const apple = document.getElementById('apple');
       document.getElementById('output').innerHTML += apple.nextElementSibling.textContent;</script></body></html>

    Accessing the Previous Sibling Node

    The previousSibling property is used to access the previous sibling node from the DOM tree.

    Syntax

    Follow the syntax below to use the previousSibling property.

    element.previousSibling;

    Example

    In the below code, we access the previous sibling of the <li> element with an id equal to 'banana. It returns the <li> element having id equal to 'apple'.

    <!DOCTYPE html><html><body><ul id ="fruit"><li id ="apple"> Apple </li><li id ="banana"> Banana </li><li id ="watermealon"> Watermealon </li></ul><div id ="output">The previous sibling node of the banana node is:</div><script>const banana = document.getElementById('banana');
    
    document.getElementById('output').innerHTML += banana.previousElementSibling.textContent;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    DOM Root Nodes

    The HTML DOM contains two root nodes.

    • document.body − It returns the <body> element of the document.
    • document.documentElement − It returns the entire HTML document.

    Example: Using the document.body

    <!DOCTYPE html><html><body><div> This is demo!</div><div id="output"></div><script>const output = document.getElementById('output');
    
    output.innerHTML +="The body of the document is: "+ document.body.innerHTML;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Example: Using the document.documentElement

    <!DOCTYPE html><html><body><h1> Hi, Users!</h1><div id="output"></div><script>const output = document.getElementById('output');
    
      output.innerHTML +="The full document is "+ document.documentElement.innerHTML;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    DOM nodeName Property

    The nodeName property of the HTML DOM element is used to get the name of the node, and it has specifications given below.

    • It is read−only. You can't modify it.
    • The value of the nodeName property is equal to the tag name in the upper case.
    • The node name of the text node is #text.
    • The node name of the document node is #document.

    Syntax

    Follow the syntax below to use the nodeName property to get the name of the node.

    element.nodeName;

    Example

    In the below code, we access the <div> element and use the nodeName property. It returns the tag name in the uppercase.

    <!DOCTYPE html><html><body><div id ="output"></div><script>const output = document.getElementById('output'); 
    
    output.innerHTML ="The node name of the div node is: "+ output.nodeName;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    DOM nodeValue Property

    The nodeValue is used to get the value of the, and it has specifications given below.

    • It is also a read-only property.
    • The node value for the text node is the text itself.
    • The node value for the element nodes is null.

    Syntax

    Follow the syntax below to use the nodeValue property to get the value of the node.

    element.nodeValue;

    Example

    The <div> element contains some text, and the <p> element in the below code.

    The first child element of the <div> element is the text node, and the second child node of the <div> element is the <p> element.

    In the output, you can see that when you use the nodeValue property with the text node, it returns the text. Otherwise, it returns null when you use it with the HTML element node.

    <!DOCTYPE html><html><body><div id ="num">
    
    Numbers
    &lt;p&gt; One &lt;/p&gt;&lt;/div&gt;&lt;div id ="output"&gt;&lt;/div&gt;&lt;script&gt;const output = document.getElementById('output');const num = document.getElementById('num');let child = num.childNodes;
    output.innerHTML +="The value of the first child is: "+ child[0].nodeValue +"&lt;br&gt;";
    output.innerHTML +="The value of the second child is: "+ child[1].nodeValue +"&lt;br&gt;";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Types of Node in DOM

    Here, we have given different node types in the HTML DOM.

    NodeTypeDescription
    Element Nodes1The element nodes can have child nodes, attributes, and text content. For example, <div>, <a>, etc., are element nodes.
    Text Nodes3The text nodes can have text content inside the node. For example, text inside the <p>, <div>, etc. elements.
    Comment Nodes8The comment nodes contain the comments.
    Document Nodes9It represents the entire document.
    Document Type Node10It represents the type of the document. For example, <!Doctype html>

    DOM nodeType Property

    The nodeType property returns the type of the node as shown in the above table.

    Syntax

    Follow the syntax below to use the nodeType property to get the type of the node.

    element.nodeType;

    Example

    In the below code, we use the nodeType property to get the type of the node.

    <!DOCTYPE html><html><body><div id ="output"></div><script>const output = document.getElementById('output');
    
    output.innerHTML +="The type of the div node is: "+ output.nodeType;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>
  • DOM Animation

    The DOM animation can be achieved by changing the DOM element’s style using JavaScript. When changes are gradual and time interval is small, the animation looks continuous. Generally, there are three ways to animate a DOM element:

    • Using CSS transitions − It utilizes pre-defined animation styles in CSS triggered by changes in the element’s properties.
    • Using CSS animations − It offers more control over animation timing and behavior by defining keyframes and animation properties within the CSS file.
    • Using JavaScript − It provides the most flexibility, allowing you to dynamically manipulate style properties and create complex animations directly within your JavaScript code.

    This chapter provides a basic understanding of how to animate DOM elements using JavaScript.

    Animate DOM Elements with JavaScript

    JavaScript can be used to change the style of the DOM element.

    You change the style of the DOM element after a particular time frame to animate them. For example, you can use the setInterval() method to change the position of the DOM element to move it from one position to another with animation.

    Similarly, you can update CSS properties like animation, etc., to animate the element dynamically.

    Furthermore, the requestAnimationFrame() method can also be used to animate the DOM elements.

    Below, you will learn different ways to animate the DOM elements.

    Animate DOM elements using setInterval() method

    You can invoke a setInterval() method after each time frame and change the style of the DOM element to animate them. However, you can keep the time frame small to run animation smoothly.

    Syntax

    Follow the syntax below to use the setInterval() method to animate DOM elements.

    let id =setInterval(frame_func, timeframe);functionframe_func(){if(animation_end){clearInterval(id);}else{// change style to animate}}

    In the above syntax, we start the animation using the setInterval() method and call the frame_func() after every timeframe milliseconds.

    In the frame_func() function, we have defined the condition to end or continue the animation.

    Example

    In the below code, we have styled the <div> elements.

    When users click the button, it calls the startAnimation() function.

    In the startAnimation() function, we have defined the pos variable and initialized it with 0, representing the initial position of the div element.

    After that, we used the setInterval() method to invoke the animationFrame() function after every 5 milliseconds.

    In the animationFrame() function, if the position of the inner div becomes 350, we stop the animation using the clearInterval() method. Otherwise, we change the left position of the inner div.

    When you click the button, it will move the inner div element from left to right.

    <!DOCTYPE html><html><head><style>
    
    #parent {
      width:700px;
      height:50px;
      position: relative;
      background: yellow;}
    #child {
      width:50px;
      height:50px;
      position: absolute;
      background-color: red;}&lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;div id ="parent"&gt;&lt;div id ="child"&gt;&lt;/div&gt;&lt;/div&gt;&lt;br&gt;&lt;button onclick ="startAnimation()"&gt; Animate Div  &lt;/button&gt;&lt;script&gt;functionstartAnimation(){const elem = document.getElementById("child");// Starting positionlet pos =0;// Changing frames for animationlet id =setInterval(animationFrame,5);functionanimationFrame(){// Stop the animationif(pos ==350){clearInterval(id);}else{
          pos++;
          elem.style.left = pos +"px";}}}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Example

    In the below code, the background color of the <div> element is green.

    We use the setInterval() method to call the animationFrame() function after every 50 milliseconds.

    In the animationFrame() function, we change the opacity of the <div> element by 0.1. We stop the animation when the opacity becomes less than or equal to 0 using the clearInterval() method.

    <!DOCTYPE html><html><head><style>
    
    #parent {
      width:700px;
      height:200px;
      background: green;}&lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;div id ="parent"&gt;&lt;/div&gt;&lt;br&gt;&lt;button onclick ="startAnimation()"&gt; Animate Div &lt;/button&gt;&lt;script&gt;functionstartAnimation(){const parent = document.getElementById("parent");let opacity =1;let id =setInterval(animationFrame,50);functionanimationFrame(){if(opacity &lt;=0){// Stop animationclearInterval(id);
          parent.style.opacity =1;
          parent.style.backgroundColor ="red";}else{// Decrease the opacity
          parent.style.opacity = opacity;
          opacity = opacity -0.1;}}}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Animate DOM elements using requestAnimationFrame() method

    The requestAnimationFrame() method is used to animate the DOM elements like the setInterval() method. It executes the tasks continuously and repaints the next frame in the browser.

    The requestAnimationFrame() method makes rendering more efficient than the setInterval() method.

    Syntax

    Follow the syntax below to use the requestAnimationFrame() method to animate DOM elements.

    functionanimate(){// Animation logic// Request the next animation framerequestAnimationFrame(animate);}// Animation loopanimate();

    Lets understand how the requestAnimationFrame() method works.

    • You pass the callback function as an argument of the requestAnimationFrame() method to execute the next frame.
    • The web browser will execute the callback before repainting the next frame.
    • The callback function will update the DOM element.
    • The browser will repaint the DOM element.
    • Again, the browser will call the callback function, and the loop will continue.

    You can use the cancelAnimationFrame() method to cancel animation.

    Example

    In the code below, we have defined the startAnimation() and stopAnimation() functions and invoked them when the user clicks the button.

    In the startAnimation() function, we increment the value of the pos by 1, and update the left position of the child div element.

    After that, we used the requestAnimationFrame() method to paint the next frame in the web browser. It will move the child div element from left to right in the parent div element.

    The stopAnimation() function uses the cancelAnimationFrame() method to stop the animation. It takes the id returned by the requestAnimationFrame() method as an argument.

    <!DOCTYPE html><html><head><style>
    
    #parent {width:700px; height:50px; position: relative;background: yellow;}
    #child {width:50px;height:50px; position: absolute; background-color: red;}&lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;div id ="parent"&gt;&lt;div id ="child"&gt;&lt;/div&gt;&lt;/div&gt;&lt;br&gt;&lt;button onclick ="startAnimation()"&gt; Animate Div &lt;/button&gt;&lt;button onclick ="stopAnimation()"&gt; Stop Animation &lt;/button&gt;&lt;script&gt;let animationId;let pos =0;functionstartAnimation(){const elem = document.getElementById("child");functionanimationFrame(){if(pos &lt;650){
          pos++;
          elem.style.left = pos +"px";// Make a call for a next frame
          animationId =requestAnimationFrame(animationFrame);}}// Start AnimationanimationFrame();}functionstopAnimation(){// Stop animationif(animationId){cancelAnimationFrame(animationId);
        animationId =null;}}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Animate DOM Elements by changing the CSS Properties

    The animation property of the CSS can be used to add animation to the DOM element. JavaScript also allows the customization of the animation property.

    Syntax

    Follow the syntax below to animate the DOM element by changing the value of the animation property of the element in JavaScript.

    element.style.animation ="key_frame_name duration timing_function iterationCount";

    Property values

    • key_frame_name − It is the name of the keyframe, which you need to define in the CSS.
    • duration − It is the duration of the animation.
    • timing_function − It is used to set how animation should be executed.
    • iterationCount − It specifies how many times the animation should repeat.

    Example

    In the below code, when users click the button, we call the animateDiv() function and update the value of the animation property of the style object of the div element.

    We have already defined the moveAnimation keyframe in CSS. So, when you click the button it will start moving the div element.

    <!DOCTYPE html><html><head><style>
    
    #element {
      width:90px;
      height:90px;
      background: blue;
      color: white;
      position: relative;
      text-align: center;}
    @keyframes moveAnimation {
      from {
        transform:translateX(0);}
      to {
        transform:translateX(550px);}}&lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;div id ="element"&gt; Animate &lt;/div&gt;&lt;br&gt;&lt;button onclick ="animateDiv()"&gt; Animate Div &lt;/button&gt;&lt;script&gt;functionanimateDiv(){const element = document.getElementById("element");
      element.style.animation ="moveAnimation 3s ease-in-out infinite";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    The best way to animate the DOM element is using the requestAnimationFrame() method, which animates the DOM element smoothly. Also, it can be used to execute different animations simultaneously.