Category: HTML DOM

  • 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.

  • Changing CSS

    Changing CSS with JavaScript

    JavaScript allows you to change the CSS of the HTML element dynamically.

    When HTML gets loaded in the browser, it creates a DOM tree. The DOM tree contains each HTML element in the object format. Furthermore, each HTML element object contains the ‘style‘ object as a property. Here, a ‘style‘ object contains various properties like color, backgroundcolor, etc., to change or get the element’s style.

    So, you can use various properties of the ‘style‘ object to change the style of the particular HTML element.

    Syntax

    Follow the syntax below to change the CSS of the HTML element.

    element.style.property = value;

    In the above syntax, ‘element’ is an HTML element, which you need to access from the DOM tree. The ‘property’ is a CSS property, and the ‘value’ can be static or dynamic.

    For example, you can change an element’s background color or font size by setting the corresponding properties on its Style Object. The best usage of this approach is for implementing dynamic behaviors, such as animations, transitions, and real-time updates to the user interface. Let’s see this in practical −

    Welcome to TutorialspointSwitch to DarkSwitch to LightIncrease Font SizeDecrease Font Size

    Example: Changing the style of the HTML element

    We have applied the initial style to the div element in the code below. In JavaScript, we change the div element’s background color using the style object’s ‘backgroundColor’ property.

    <!DOCTYPE html><html><head><style>
    
    div {
      background-color: blue;
      width:700px;
      height:100px;
      color: white;}&lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;div id ="square"&gt; Changing the color ofthis Div.&lt;/div&gt;&lt;br&gt;&lt;button onclick="changeColor()"&gt; Change Color &lt;/button&gt;&lt;script&gt;functionchangeColor(){let square = document.getElementById('square');
      square.style.backgroundColor ='red';}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Changing Style of the Element When Event Triggers

    You can also change the style of the element when a particular event triggers.

    Example

    In the below code, we added the 'click' event to the <div> element. When users click the button, it changes the background color of the div element.

    <!DOCTYPE html><html><head><style>
    
    div {
      width:700px;
      height:100px;
      color: white;
      background-color: orange;}&lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;div id ="square"&gt; Click Me &lt;/div&gt;&lt;br&gt;&lt;script&gt;const square = document.getElementById('square');
    square.addEventListener('click',()=&gt;{
      square.style.backgroundColor ='green';
      square.style.fontSize ="25px";});&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Changing CSS of HTML elements Dynamically

    You can also change the CSS of the HTML element dynamically. You can assign values using the variables.

    Example

    We have added the default style to the <div> element in the code below.

    Also, we have created multiple radio buttons. When users select any radio button, it changes the style of the div element accordingly.

    <!DOCTYPE html><html><head><style>
      p {
    
    width:700px;
    height:100px;
    color: white;
    background-color: blue;}&lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;div&gt;&lt;p id ="square"&gt;Select any of the following colors to change the background color&lt;/p&gt;&lt;/div&gt;&lt;div&gt;Yellow:&lt;input type ="radio" id ="yellow" name ="color"&gt;&lt;/div&gt;&lt;div&gt;Green:&lt;input type ="radio" id ="green" name ="color"&gt;&lt;/div&gt;&lt;div&gt;Red:&lt;input type ="radio" id ="red" name ="color"&gt;&lt;/div&gt;&lt;script&gt;let square = document.getElementById('square');//    Changing the style when radio button changeslet colors = document.getElementsByName('color');for(let i =0; i &lt; colors.length; i++){
    colors[i].addEventListener('change',function(){
      square.style.backgroundColor =this.id;});}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    List of JavaScript DOM Style Object Properties

    Following is a list of properties provided by JavaScript DOM Style Object −

    Sr.NoProperties & Description
    1alignContentIt aligns the flexible container's item on the cross-axis or vertical axis when they do not use all available spaces.
    2alignItemsIt sets the default alignment of items inside a flexible container.
    3alignSelfIt sets the default alignment of a single flex item along the cross axis within a flexible container.
    4animationIt define the desired styles.
    5animationDelayIt sets the delay time in seconds or milliseconds after which animation should start.
    6animationDirectionIt sets the direction of animation.
    7animationDurationIt specifies the time it takes for an animation to complete one cycle.
    8animationFillModeIt specifies the style of an element when the animation is not playing, has ended, or contains a delay.
    9animationIterationCountIt sets or returns the number of times an animation should be played.
    10animationNameIt gets or sets the animation name for @keyframes animation.
    11animationTimingFunctionIt specifies the speed curve of an animation.
    12animationPlayStateIt specifies whether an animation is running or paused.
    13backgroundIt sets or returns up to 8 separate background properties of an element.
    14backgroundAttachmentIt sets or returns whether the background image should scroll with the content or remain fixed.
    15backgroundColorIt sets or returns the background color of an element.
    16backgroundImageIt sets or returns the background image of an element.
    17backgroundPositionIt sets or returns the position of the background image of an element.
    18backgroundRepeatIt sets or returns how a background image is to be repeated.
    19backgroundClipIt sets or returns the painting area of the background.
    20backgroundOriginIt sets or returns the relative position of a background image with respect to padding, border, and content.
    21backgroundSizeIt sets or returns the size of the background image.
    22backfaceVisibilityIt specifies whether the element should be visible or not when it's not facing the screen.
    23borderIt sets or returns the border properties of an element.
    24borderBottomIt sets or returns the border-bottom properties of an element.
    25borderBottomColorIt sets or returns the color of the bottom border of an element.
    26borderBottomLeftRadiusIt sets or returns the radius of the bottom border of the left corner.
    27borderBottomRightRadiusIt sets or returns the radius of the bottom border of the right corner.
    28borderBottomStyleIt sets or returns the border-bottom style of an element.
    29borderBottomWidthIt sets or returns the border-bottom width of the element.
    30borderCollapseIt specifies whether table cell elements should have separate borders or share a single border that is collapsed into a single border.
    31borderColorIt sets or returns the border color of an element.
    32borderImageIt sets or returns the border image of an element.
    33borderImageOutsetIt specifies the border image area amount by which it extends beyond the border box.
    34borderImageRepeatIt sets or returns whether the image border should be rounded, repeated, or stretched.
    35borderImageSliceIt specifies the inward offsets of the image border.
    36borderImageSourceIt sets or returns the source of the image to be used as a border image for an element.
    37borderImageWidthIt sets or returns the width of the image border.
    38borderLeftIt sets or returns the left border properties of an element.
    39borderLeftColorIt sets or returns the color of the left border of an element.
    40borderLeftStyleIt sets or returns the left border style of an element.
    41borderLeftWidthIt sets or returns the left border width of the element.
    42borderRadiusIt sets or returns four different border-radius properties.
    43borderRightIt sets or returns the right border properties of an element.
    44borderRightColorIt sets or returns the color of the right border of an element.
    45borderRightStyleIt sets or returns the right border style of an element.
    46borderRightWidthIt sets or returns the right border width of the element.
    47borderSpacingIt sets or returns the space between cells in the table.
    48borderStyleIt sets or returns the border style of an element.
    49borderTopIt sets or returns the top border properties of an element.
    50borderTopColorIt sets or returns the color of the top border of an element.
    51borderTopLeftRadiusIt sets or returns the border radius of the top left corner.
    52borderTopRightRadiusIt sets or returns the border radius of the top right corner.
    53borderTopStyleIt sets or returns the top border style of an element.
    54borderTopWidthIt sets or returns the top border width of the element.
    55borderWidthIt sets or returns the border width of the element.
    56bottomIt sets or returns the bottom position of a positioned element.
    57boxShadowIt sets or gets the shadow around or inside the element's frame.
    58boxSizingIt specifies the way an element's total width and height is calculated.
    59captionSideIt sets or returns the table caption position.
    60caretColorIt sets or gets the cursor color of any editable element, in inputs or areas.
    61clearIt sets or gets the relative position of a specific element with respect to floating objects.
    62clipIt sets or gets the visible part of a positioned element.
    63colorIt sets or gets the text color of the selected element.
    64columnCountIt specifies the number of columns into which an element should be divided.
    65columnFillIt specifies how contents will be arranged in columns when broken into various columns.
    66columnGapIt specifies the gap between the columns.
    67columnRuleIt sets or returns column rule properties.
    68columnRuleColorIt sets or gets the rule color between columns.
    69columnRuleStyleIt sets or gets the rule style between the columns.
    70columnRuleWidthIt sets or gets the rule width between the columns.
    71columnsIt sets the column Width and column Count.
    72columnSpanIt defines the number of columns on which an element should span across.
    73columnWidthIt sets or gets the width of the columns.
    74counterIncrementIt defines the number of counters to be increased on each occurrence of any selector.
    75counterResetIt creates or resets the Counter.
    76cursorIt sets or gets the type of cursor to be displayed for the mouse pointer.
    77directionIt sets or gets the text direction of an element.
    78displayIt sets or returns the display type of an element.
    79emptyCellsIt sets or gets whether to display or not the border and background property of empty cells.
    80filterIt adds filters or visual effects to an image.
    81flexIt sets or gets whether to display or not the border and background property of empty cells.
    82flexBasisIt sets or returns the initial length of a flexible item.
    83flexDirectionIt sets or returns the direction of placement of flex elements.
    84flexFlowIt specifies the direction of the flexible items and flex-wrap specifies whether the flexible items should be wrapped.
    85flexGrowIt specifies the growth of an item relative to the rest of the flexible items inside the same container.
    86flexShrinkIt specifies how much the item will shrink relative to the rest of the flexible items inside the same container.
    87flexWrapIt specifies whether flexible items should be wrapped.
    88cssFloatIt sets or returns the horizontal alignment of an element.
    89fontIt sets or returns font properties.
    90fontFamilyIt sets or returns a list of font-family names and generic-family names for text in an element.
    91fontSizeIt sets or returns the font size of the text.
    92fontStyleIt sets or returns the font style of an element.
    93fontVariantIt sets or returns texts in small and capital letters.
    94fontWeightIt sets or returns the font-weight property which specifies the thickness of characters in a word.
    95fontSizeAdjustIt sets or returns the font aspect value of the text.
    96heightIt sets or returns the height of an element.
    97isolationIt specifies whether an element must create a new stacking content.
    98justifyContentIt sets or returns the alignment of flex items on the main axis or horizontally when they do not use all the available spaces.
    99leftIt sets or returns the left position of a positioned element.
    100letterSpacingIt sets or returns the space between characters of text.
    101lineHeightIt sets or returns the distance between lines in a text.
    102listStyleIt sets or returns the following three properties.
    103listStylePositionIt positions the list item marker.
    104listStyleImageIt sets an image as a list item marker.
    105listStyleTypeIt sets or gets the marker type of list items.
    106marginIt sets or returns the margins of an element.
    107marginBottomIt sets or returns the bottom margin of an element.
    108marginLeftIt sets or returns the left margin of an element.
    109marginRightIt sets or returns the right margin of an element.
    110marginTopIt sets or returns the top margin of an element.
    111maxHeightIt sets or returns the maximum height of an element.
    112maxWidthIt sets or returns the maximum width of an element.
    113minHeightIt sets or returns the minimum height of an element.
    114minWidthIt sets or returns the minimum width of an element.
    115objectFitIt sets or returns how an image or video is to be resized to fit its container.
    116objectPositionIt defines how an image or video should be positioned in its content box.
    117opacityIt sets or returns the opacity level or transparency level of an element where 0 represents completely transparent and 1 represents not transparent at all.
    118orderIt sets or returns the order of the flexible items relative to flex items in the same container.
    119orphansIt sets or returns the minimum number of lines visible at the bottom of the page for an element.
    120outlineIt sets or returns the following three outline properties.
    121outlineColorIt sets or returns the outline color around an element.
    122outlineOffsetIt sets or returns an outline offset and draws it beyond the border edge.
    123outlineStyleIt sets or returns the outline style around an element.
    124outlineWidthIt sets or returns the outline width of the element.
    125overflowIt decides on what to do with the content which does not fit inside the element box.
    126overflowXIt decides what to do with the left and right edges of content if it does not fit inside the element box.
    127overflowYIt decides what to do with the top and bottom edges of content if it does not fit inside the element box.
    128paddingIt sets or returns the padding of an element.
    129paddingBottomIt sets or returns the bottom padding of an element.
    130paddingLeftIt sets or returns the left padding of an element.
    131paddingRightIt sets or returns the right padding of an element.
    132paddingTopIt sets or returns the top padding of an element.
    133pageBreakAfterIt sets or returns the page break behavior after an element during print or print preview.
    134pageBreakBeforeIt sets or returns the page break behavior before an element during print or print preview.
    135pageBreakInsideIt sets or returns page break behavior inside an element during print or print preview.
    136perspectiveIt specifies the distance that, how far an element is placed from the z=0 plane to provide a 3D view of an element.
    137perspectiveOriginIt sets the position of a 3D element using the x-axis and y-axis.
    138positionIt sets or returns the type of positioning method used on any element.
    139quotesIt sets or returns the type of quotation marks for embedded quotations.
    140resizeIt specifies whether a user can resize or change the height and width of an element or not.
    141rightIt sets or returns the right position of a positioned element including padding, scrollbar, border, and margin.
    142scrollBehaviorIt specifies a smooth scroll effect instead of scrolling instantly when the user clicks on a link within the scrollable box.
    143tableLayoutIt sets or returns the way table cells, rows, and columns are laid out in an HTML document.
    144tabSizeIt sets or returns the length of the space used for the tab character.
    145textAlignIt sets or returns the horizontal alignment of text content inside the block-level element.
    146textAlignLastIt sets or returns the alignment of the last line of text.
    147textDecorationIt sets the textDecorationLine, textDecorationStyle, and the textDecorationColor properties.
    148textDecorationColorIt sets or returns the color of text decoration like overline, underline, and line-through.
    149textDecorationLineIt specifies the type of line the decoration will have.
    150textDecorationStyleIt sets or returns the style of text decoration line like it can be displayed as solid, dashed, dotted, or wavy.
    151textIndentIt sets or returns the indentation of the first line of text.
    152textOverflowIt specifies the behavior of text when it overflows the containing element.
    153textShadowIt sets or returns one or more text-shadow effects.
    154textTransformIt sets or returns the capitalization of text.
    155topIt sets or returns the top position of apositionedelement including margin, border, padding, and scrollbar.
    156transformIt applies a 2D or 3D transformation to transform the object.
    157transformOriginIt allows the user to change the position of transformed elements.
    158transformStyleIt specifies whether child elements are positioned in 3D space or flattened with respect to the plane of the parent element.
    159transitionIt adds an animation-like effect while changing the CSS property of any block-level element when hovered over it.
    160transitionDelayIt sets or returns the delay time in seconds or milliseconds after which the transition effect will start.
    161transitionDurationIt sets or returns the amount of time in seconds or milliseconds, that a transition effect takes to complete.
    162transitionPropertyIt specifies the CSS property name on which the transition effect will be applied.
    163transitionTimingFunctionIt sets or returns the speed curve of the transition effect.
    164unicodeBidiIt specifies how bidirectional text in a document is displayed.
    165userSelectIt sets or returns whether the text can be selected by the user or not.
    166verticalAlignIt sets or returns the vertical alignment of the content in an element.
    167visibilityIt sets or returns whether an element should be visible or not.
    168whiteSpaceIt sets or returns the way how whitespaces are being handled in a text.
    169widthIt sets or returns the width of an element.
    170windowIt sets or returns the minimum number of lines visible at the top of the page for an element.
    171wordBreakIt specifies how words should break when they reach at end of the line except for CJK (Chinese, Japanese, and Korean) scripts.
    172wordSpacingIt sets or returns spacing between words of the sentences.
    173wordWrapIt sets or returns whether long words should be broken to wrap onto the next line.
    174zIndexIt sets the z-order of a positioned element.

  • Changing HTML

    Changing HTML with JavaScript

    The HTML DOM allows us to change the HTML elements with JavaScript. You can customize or dynamically update the HTML elements using the various methods and properties. For example, you can change the content of the HTML element, remove or add new HTML elements to the web page, change a particular element’s attribute’s value, etc.

    In JavaScript, we can access the HTML elements using id, attribute, tag name, class name, etc. After accessing the elements, we can change, manipulate them using the properties such as innerHTML, outerHTML, etc. and methods such as replaceWith(), appendChild() etc.

    Changing HTML Using innerHTML Property

    The innerHTML property of the HTML property is used to replace the HTML content of the element or add new HTML elements as children of the current element.

    Syntax

    Follow the syntax below to use the innerHTML property to change the HTML.

    element.innerHTML = HTML_str;

    In the above syntax, ‘element’ is an HTML element accessed in JavaScript, and HTML_str is an HTML in the string format.

    Example

    In the example below, we replace the HTML content of the div element using the innerHTML property. You can click the button to replace the HTML content in the output.

    <html><body><div id ="text"><p> One </p><p> Two </p></div><button onclick ="changeHTML()"> Change HTML</button><script>functionchangeHTML(){let text = document.getElementById('text');
    
         text.innerHTML =&amp;lt;div&amp;gt; JavaScript &amp;lt;/div&amp;gt; &amp;lt;div&amp;gt; HTML &amp;lt;/div&amp;gt; &amp;lt;div&amp;gt; CSS &amp;lt;/div&amp;gt;;}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Changing HTML Using outerHTML Property

    The outerHTML property of the HTML element replaces the HTML of the element, including the tags.

    Syntax

    Follow the syntax below to use the outerHTML property.

    element.outerHTML = HTML_str;

    The HTML_str is an HTML content in the string format.

    Example

    In the below code, we replace the <div> element with the <img> element when users click the button using the outerHTML property.

    <html><body><div id ="text"><p> Paragraph One </p><p> Paragraph Two </p></div><p></p><button onclick ="changeHTML()"> Change HTML</button><script>functionchangeHTML(){let text = document.getElementById('text');
    
         text.outerHTML =&amp;lt;img src="https://www.tutorialspoint.com/static/images/logo.png?v3" alt="Logo"&amp;gt;;}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Replacing HTML Element Using replaceWith() Method

    The replaceWIth() method replaces the particular HTML element with a new element.

    Syntax

    Follow the syntax below to use the replaceWith() method to change the HTML.

    Old_lement.replaceChild(new_ele);

    You need to take the existing element as a reference of the replaceChild() method and pass the new element as an argument.

    Example

    In the below code, we used the createElement() method to create a new <p> element. After that, we added the HTML into that.

    Next, we have replaced the div element with the new element in the changeHTML() function.

    <html><body><div id ="text">Hello World!</div><button onclick ="changeHTML()"> Change HTML</button><script>functionchangeHTML(){const text = document.getElementById('text');const textNode = document.createElement('p');
    
         textNode.innerHTML ="Welcome to the Tutorialspoint!";// Using the replaceWith() method
         text.replaceWith(textNode);}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Changing Value of HTML Element's Attribute

    You can access the HTML element and set its value in JavaScript.

    Syntax

    Follow the syntax below to change the value of the HTML element's attribute.

    element.attribute = new_value;

    Here, 'attribute' is needed to replace the HTML attribute. The 'new_value' is a new value of the HTML attribute.

    Example

    In the below code, we change the value of the 'src' attribute of the <img> element. When you click the button, it will change the image.

    <html><body><img src ="https://www.tutorialspoint.com/static/images/logo.png?v3" width ="300px" id ="logoImg" alt ="logo"><p></p><button onclick="changeURL()"> Change URLof Image </button><script>functionchangeURL(){
    
         document.getElementById('logoImg').src ="https://www.tutorialspoint.com/static/images/simply-easy-learning.png";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Adding a New Element to the HTML Element

    You can use the appendChild() method to add a new HTML child to the particular HTML element.

    Syntax

    Follow the syntax below to add a new element using the appendCHild() method.

    element.appendChild(new_ele);

    You need to use the parent element as a reference of the appendChild() method and pass the new element as an argument.

    Example

    In the below code, we append the <p> Apple <p> as a child of the <div> element.

    <html><body><div id ="fruits"><p> Banana </p><p> Watermelon </p></div><button onclick ="AddFruit()"> Add Apple </button><script>functionAddFruit(){const fruits = document.getElementById("fruits");const p = document.createElement("p");
    
         p.innerHTML ="Apple";
         fruits.appendChild(p);// Using the appendChild() method}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Removing a Child Element from the HTML Element

    You can use the removeChild() method to remove the child element from the particular HTML element.

    Syntax

    Follow the syntax below to use the removeChild() method.

    element.removeChild(child_ele)

    You need to use the HTML element as a reference of the removeChild() method when you need to remove the child element and pass the child element as an argument.

    Example

    In the below code, we remove the <p> Apple <p> from the <div> element.

    <html><body><div id ="fruits"><p> Banana </p><p> Watermelon </p><p> Apple </p></div><button onclick ="removeFruit()"> Remove Apple </button><script>functionremoveFruit(){const fruits = document.getElementById("fruits");const apple = fruits.children[2];
    
        fruits.removeChild(apple);}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Using the document.write() Method

    The document.write() method replaces the whole content of the web page and writes a new HTML.

    Syntax

    Follow the syntax below to use the document.write() method.

    document.write(HTML);

    The document.write() method takes an HTML in the string format as a parameter.

    Example

    In the below code, we replace the content of the whole web page using the document.write() method.

    <html><body><div id ="fruits"><p> Banana </p><p> WaterMealon </p><p> Apple </p></div><button onclick="replaceContent()"> Replace content </button><script>functionreplaceContent(){
    
         document.write("Hello World");}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    For more practice, you may try to change the first child element, last child element, other attributes, etc. of the HTML elements.

  • DOM Forms

    The DOM Forms

    The HTML DOM document forms are used to get the data from the users.

    In JavaScript, you can use the ‘forms’ collection of the ‘document’ object to access all <form> elements of the HTML document.

    You can access all forms elements of particular forms and manipulate them. Using JavaScript, you can validate the form values, handle the form data submission, etc.

    Syntax

    Follow the syntax below to use the ‘forms’ collection to manipulate the forms of the DOM.

    document.forms;

    Here, ‘forms’ is a property of the ‘document’ object.

    Properties of ‘forms’ Collection

    PropertyDescription
    lengthIt represents the number of <form> elements in the HTML document.

    Methods of ‘forms’ Collection

    MethodDescription
    [index]To get the particular <form> element from the 0-based index of the collection of HTML forms.
    item(index)To get the particular <form> element from the 0-based index of the collection of HTML forms.
    namedItem(id)To get the <form> element with a particular id.

    Return value

    The document.forms returns the collection of all forms in the same order as they are present in the HTML document.

    Example: Finding total <form> elements in the HTML document)

    In the below code, we use the ‘length’ property of the ‘forms’ collection to find the number of existing forms in the HTML document.

    <html><body><form><input type ="text" name ="first" id ="first" value ="First Name"></form><form><input type ="text" name ="second" id ="second" value ="Last Name"></form><form><input type ="text" name ="third" id ="third" value ="Contact"></form><div id ="output">Total number of forms in the HTML document is:</div><script>
    
    document.getElementById('output').innerHTML += document.forms.length;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Example: Get the id of all <form> elements

    In the below code, we access each form using its index and use the 'id' property to get the id of a particular form.

    <html><body><form id ="form1"><label for="first"> Fruit Name:</label><input type ="text" name ="first" id ="first"></form><form id ="form2"><label for="second"> Price:</label><input type ="text" name ="second" id ="second"></form><form id ="form3"><label for="third"> Color:</label><input type ="text" name ="third" id ="third"></form><div id ="output"></div><script>
      document.getElementById('output').innerHTML ="Id of the first form is: "+ document.forms[0].id +"<br>"+"Id of the second form is: "+ document.forms[1].id +"<br>"+"Id of the third form is: "+ document.forms[2].id;</script></body></html>

    Example: Get particular form using its id and namedItem() method

    In the code below, we used the namedItem() method by taking the 'forms' collection as a reference to get a form with a particular id.

    <html><body><form id ="form1"><label for="first"> First Name </label><input type ="text" name ="first" id ="first"></form><form id ="form2"><label for="second"> Last Name </label><input type ="text" name ="second" id ="second"></form><div id ="output">The innerHTML of the form element having id equal to form2 is:</div><script>const output = document.getElementById('output');
    
    output.innerHTML += document.forms.namedItem('form2').innerHTML;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    JavaScript Form Submission

    In JavaScript, you can submit the form using the 'submit' input type and execute a particular function to handle the form data using the onsubmit() event handler.

    Example

    In the below code, the form takes users' first and last names. After that, when users click the submit input, it calls the submitForm() function.

    In the submitForm() function, we used the preventDefault() method to prevent the execution of the function without submitting the form.

    After that, we use the 'forms' collection to access the form and values of its input fields.

    At last, we print the input values in the output.

    <html><body><form onsubmit ="submitForm(event)" id ="nameform"><p><label>First Name:</label><input type ="text" name ="firstname"></p><p><label>Last Name:</label><input type ="text" name ="lastname"></p><p><input type ="submit"></p></form><div id ="output"></div><script>functionsubmitForm(e){
    
    e.preventDefault();const output = document.getElementById('output');const firstname = document.forms['nameform']['firstname'].value;const lastname = document.forms['nameform']['lastname'].value; 
    output.innerHTML ="First Name: "+ firstname +", Last Name: "+ lastname;}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    JavaScript Form Validation

    In JavaScript, you can also validate the form to ensure the users have filled the required inputs. You can perform the validation check in the function that you are invoking on form submit.

    Furthermore, you may also show the error message in the output if the form is not fulfilling the particular condition.

    Example

    In the below code, we check whether the length of the first name and last name is less than 3 when users submit the form. If the length of firstname or lastname is less than 3, we show the error message.

    <html><body><form onsubmit ="submitForm(event)" id ="nameform"><p>First Name:<input type ="text" name ="firstname"></p><p>Last Name:<input type ="text" name ="lastname"></p><p><input type ="submit"></p></form><div id ="output"></div><script>functionsubmitForm(e){
    
    e.preventDefault();const output = document.getElementById('output');const firstname = document.forms['nameform']['firstname'].value;const lastname = document.forms['nameform']['lastname'].value;if(firstname.length &lt;3|| lastname.length &lt;3){
      output.innerHTML +="The length of the first name or last name should be greater than 3. &lt;br&gt;";}else{
      output.innerHTML ="First Name: "+ firstname +", Last Name: "+ lastname;}}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    JavaScript Form Data Validation

    It is also required to validate the input data.

    Sometimes, it happens that you want users to pass the numeric data, but they pass the string data by mistake. In such cases, developers are required to validate the data and show the error message.

    You may validate the data on the client side or server side. It is a best practice to validate the data on the client side and send pure data to the server.

    Example

    In the code below, we have created the input field to take emails from users. When users submit the form, we use the regex and test() method to check whether they have passed the valid email address in the input.

    <html><body><form onsubmit ="submitForm(event)" id ="emailform"><p>Email:<input type ="email" name ="email"></p><p><input type ="submit"></p></form><div id ="output"></div><script>functionsubmitForm(e){
    
      e.preventDefault();const email = document.forms['emailform']['email'].value;//Validate email using regexconst emailRegex =/^[a-z0-9]+@[a-z]+\.[a-z]{2,3}$/;if(emailRegex.test(email)){
        document.getElementById('output').innerHTML ="Email is valid!";}else{
        document.getElementById('output').innerHTML ="Email is not valid!";}}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Form Validation Using the HTML Constraint

    (Automatic form validation)

    In HTML5, some constraints are introduced to validate the form. You can use these constraints as an attribute of the HTML element, and it prevents the form submission if the input doesn't match the constraints.

    The table below contains the constraints and their description.

    ConstraintDescription
    disabledTo disable the input element.
    maxTo specify the maximum value of the input element.
    minTo specify the minimum value of the input element.
    patternTo specify the particular pattern for the input element.
    requiredTo specify the input element as a required field.
    typeTo specify the type of the input element.

    Syntax

    Follow the syntax below to add the above constraints as an attribute to the <input> element.

    <input attr=value >

    Example: Using the required attribute

    In the below code, we used the 'required' attribute with the input element. When you submit the form without entering the number in the input field, it will show a default error message.

    <html><body><form onsubmit ="submitForm(event)" id ="form"><p>Number:<input type ="number" name ="num" required></p><p><input type ="submit"></p></form><div id ="output"></div><script>functionsubmitForm(e){
    
      e.preventDefault();const num = document.forms['form']['num'].value;
      document.getElementById('output').innerHTML +="The submitted numeric value is: "+ num +"&lt;br&gt;";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    The HTML form validation constraints provide limited functionality. So, you can write a custom JavaScript function to validate the form.

    You may also use the CSS selectors to validate the form.

  • DOM Attribute

    The attribute interface in the Document Object Model (DOM) represents attributes of an element as an object. And, this object represents an HTML attribute, through which we can control the functionality of HTML elements.

    The attributes of an element are stored in an array-like unordered collection called NamedNodeMap. You can access nodes of this array using its name or index. The indexing starts from 0.

    For example, the src attribute of an <img> element defines the path to the image to be displayed. Let’s see how to get the name of id attribute −

    HTML DOM Attribute name Property

    Example

    The code for above example is given below −

    <!DOCTYPE html><html><head><title>HTML DOM Attribute name Property</title><style>
    
        .my_exe{
            width: 95%;
            padding: 10px;
            margin: 5px auto;
            background-color: rgb(197, 245, 221);
            border-radius: 10px;
            box-shadow: rgba(0, 0, 0, 0.24) 0px 3px 8px;
            font-family: sans-serif;
        }
        .my_exe h3, .my_exe p, .my_exe img{
            text-align: center;
            justify-content: center;
            align-items: center;
        }
        .my_exe img{
            border: 1px solid green;
            border-radius: 5px;
            cursor: pointer;
            padding: 10px;
        }
        .my_exe input{
            display: block;
            width: 350px;
            padding: 10px;
            font-size: 18px;
            border-radius: 5px;
            outline: none;
            border: none;
            display: flex;
            margin: 10px auto;
        }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;div class="my_exe"&gt;&lt;h3&gt;HTML DOM Attribute name Property&lt;/h3&gt;&lt;p&gt;Click on the below image to get it's attribute&lt;/p&gt;&lt;img id="demo" src="https://www.tutorialspoint.com/images/logo.png" alt="demo image" onclick="printAttribute()"/&gt;&lt;input type="text" id="attribute-box" placeholder="Attribute of img tag..." readonly/&gt;&lt;/div&gt;&lt;script&gt;
        function printAttribute() {
            const element = document.getElementById("demo");
            let aName = element.attributes[0].name;
            document.getElementById("attribute-box").value = aName;
        }
    &lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    HTML DOM Attribute Properties

    The following table contains a list of DOM Attribute properties −

    Sr.NoProperties & Description
    1.valueThis property is used to set or get the value of an attribute.
    2.specifiedIt checks whether the mentioned attribute is specified or not.
    3.nameIt is used get the name of the used attribute on an element.
    4.isIdThis property determines whether a HTML attribute is an 'id' attribute or not.

  • DOM Elements

    The DOM Elements

    The HTML DOM elements is the acronym for the Document Object Model elements. With JavaScript, we can manipulate the HTM elements. We can access the HTML elements using id, attribute, tag name, class name, etc.

    When a web page loads in the browser, it creates a DOM tree representing the web page’s structure. The web page contains various HTML elements, which you can manipulate using the properties and methods in JavaScript. Here we will discuss to access, modify, or replace, etc. DOM elements.

    Accessing DOM elements

    You can use different methods to access HTML elements, as given below.

    Get HTML Element using its “id”

    In the web page, each HTML element can have a unique id value. You can use the getElementById() method to access the HTML element using the id.

    Syntax

    Follow the syntax below to use the getElemenetById() method to access the HTML element using its id.

    document.getElementById('id')

    In the above syntax, you need to replace the ‘id’ with the actual id of the element.

    Example

    In the below code, we access the div element using id and change its inner HTML using the ‘innerHTML’ property.

    <html><body><div id ="output"></div><script>
    
      document.getElementById('output').innerHTML ="The element is accessed using the id.";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The element is accessed using the id.
    

    Get an HTML element using the "name"

    An HTML can have a 'name' attribute. You can use the getElementByName() method to access the HTML element using the 'name' attribute's value.

    Syntax

    Follow the syntax below to use the getElementByName() method.

    document.getElementsByName('name')

    Here, you need to replace the 'name' with a value of the element's name attribute.

    Example

    In the below code, we access the div element using the name. It returns the array of nodes with the name passed as an argument.

    <html><body><div name ="text"> Hello World!</div><div id ="output">The content of the div elment is:</div><script>const divEle = document.getElementsByName('text');
    
      document.getElementById("output").innerHTML += divEle[0].innerHTML;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Hello World!
    The content of the div elment is: Hello World!
    

    Get HTML element using the "className"

    The class attribute of the HTML contains the string value. A single HTML element can also have multiple classes. You can use the getElementByClassName() method to access the HTML element using any single class name among multiples.

    Syntax

    Follow the syntax below to use the getElementByClassName() method.

    document.getElementsByClassName('className');

    In the above syntax, replace the 'className' with the value of the elment's 'class' attribute.

    Example

    In the below code, we access the div element using the class name.

    <html><body><div class="fruit"> Apple </div><div id ="output">The name of the fruit is:</div><script>const divEle = document.getElementsByClassName('fruit');
    
      document.getElementById("output").innerHTML += divEle[0].innerHTML;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Apple
    The name of the fruit is: Apple
    

    Get an HTML element using the "tag" name

    Each HTML element is defined using the HTML tag. You can use the tag getElementByTagName() method to access the HTML elements using the tag name.

    Syntax

    Follow the syntax below to use the getElementByTagName() method.

    document.getElementsByTagName('tag');

    In the above syntax, replace the 'tag' with the HTML tag like 'p', 'a', 'img', etc.

    Example

    In the below code, we access the <p> elements using the getElementTagName() method.

    It returns the Nodelist of <p> elements.

    <html><body><p>This is the first paragraph.</p><p>This is the second paragrraph.</p><div id ="output"></div><script>const numbers = document.getElementsByTagName('p');
       document.getElementById("output").innerHTML ="The first 'p' element is: "+ numbers[0].innerHTML +"<br>"+"The second 'p' element is: "+ numbers[1].innerHTML;</script></body></html>

    Output

    This is the first paragraph.
    
    This is the second paragrraph.
    
    The first 'p' element is: This is the first paragraph.
    The second 'p' element is: This is the second paragrraph.
    

    Modifying the DOM Elements

    JavaScript allows you to modify and replace the HTML DOM elements.

    In this section, we will cover modifying DOM elements' content and replacing child elements.

    Modify the Content of the DOM Element

    You can use the 'textContent' property of the element to modify the text of the HTML element. However, you can use other properties like innerHTML, outerHTML, outerText, etc., to modify the HTML element's content.

    Syntax

    Follow the syntax below to use the textContent property to modify the text content of the HTML element.

    element.textContent = newText;

    In the above syntax, we have assigned the 'newText' dynamic value to the 'textContent' property to update the content of the 'element'.

    Example

    In the output, when you click the button, it will invoke the updateText() function and uses the textContent property to change the text of the div element.

    <html><body><button onclick ="updateText()"> Update Text </button><p id ="text"> Hello World!</p><script>functionupdateText(){
    
         document.getElementById("text").textContent ="This is updaetd text!";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Replace the Child Element

    In JavaScript, you can use the replaceChild() method to replace the child element of the particular HTML element.

    Syntax

    Follow the syntax below to use the replaceChild() method in JavaScript.

    textDiv.replaceChild(newNode,replacableNode);

    The replaceChild() method takes a new node as a first parameter and a node that needs to be replaced as a second parameter.

    Example

    In the below code, we used the replaceChild() method to replace the second child of the div element with a new node. Here, we have also used the createTextNode() to create a new node with a 'Hello World!' text.

    <html><body><button onclick ="replaceText()"> Replace Child </button><div id ="text"><p> Hi Users!</p></div><script>functionreplaceText(){let textDiv = document.getElementById("text");let newText = document.createTextNode("Hello World");
    
         textDiv.replaceChild(newText, textDiv.childNodes[1]);}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Adding Events to the DOM Elements

    You can use addEventListner() method to add events to the DOM elements to interact with the HTML elements.

    Syntax

    Follow the syntax below to use the addEventListner() method.

    element.addEventListener(eventName, callback);

    The addEventListner() method takes an event name as the first parameter and a callback function as a second parameter.

    Example

    We added the click event on the div element in the code below. The div element will print a message on the web page whenever you click it.

    <html><body><div id ="text" style ="background-color: red;color:white"><p> Some text </p><p> Some other text </p></div><div id ="output"></div><script>let text = document.getElementById("text");
    
      text.addEventListener("click",function(){
         document.getElementById("output").innerHTML ="You clicked on the div element";});&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    List of JavaScript DOM Element Methods

    The following table shows a list of JavaScript DOM element methods −

    Sr.NoMethod & Description
    1.toString()It is used to convert an HTML element into a string format.
    2.setAttribute()This method allows you to define attributes for a particular element.
    3.setAttributeNode()This method allows you to define a particular attribute node on a particular element.
    4.scrollIntoView()It ensures that a particular element on a web page of scrollable container becomes visible by adjusting the scroll position.
    5.querySelector()It is used to select and access the first HTML element that matches a given CSS selector(s) within the document.
    6.querySelectorAll()This method allows you to select and access all HTML element that matches a given CSS selector(s) within the document.
    7.remove()This method can delete an element completely from the web page.
    8.removeAttribute()This method is used to delete any attribute that has been set on an HTML element within the DOM structure.
    9.removeAttributeNode()It allows you to delete a specific attribute node from an element.
    10.removeChild()It is used to delete the selected child element from its parent element.
    11.removeEventListener()This method allows you to delete an event listener that was previously assigned to an element.
    12.replaceChild()This method enable us to replace one child element with another in a parent element.
    13.hasAttribute()It is used to check whether an attribute exists within an HTML element.
    14.hasAttributes()This method checks whether an element in HTML DOM has attributes.
    15.hasChildNodes()It is used to check if an HTML element has any child element inside it.
    16.getAttribute()It returns the value of a specified attribute that belongs to an HTML element.
    17.getBoundingClientRect()This method is used to get the size of an element and its position relative to the viewport.
    18.closest()This method returns the closest ancestor of the current element (or the current element itself) that matches a given CSS selector. If no such ancestor exists, it returns null.
    19.contains()You can check if a DOM Element contains another element within its subtree using this method.
    20.click()The click() method activates a mouse click on an element.
    21.normalize()It is used to combine adjacent text nodes within an HTML element by removing any empty text nodes.
    22.isDefaultNamespace()It is used to check if a specific namespace URI is the default namespace for elements within a document or element.
    23.isEqualNode()This method checks if two nodes are equal by comparing their attributes, types, and child nodes.
    24.isSameNode()It checks whether two node references point to the same node object within an HTML document.
    25.isSupported()This method is used to check if a web browser can supports or handle a particular feature or functionality on a web page.
    26.insertAdjacentElement()This method allows you to insert a new HTML element exactly where you need it relative to another element on a webpage.
    27.insertBefore()This method allows you to add a new child element inside a parent element, specifying its position relative to another child element.
    28.blur()This method allows you to dynamically remove focus from an element in the HTML DOM.
    29.matches()This method checks if an element matches a given CSS selectors.
    30.insertAdjacentHTML()It helps you to insert a specified HTML code at a specific position relative to the element that calls this method.
    31.addEventListener()It is used to register event handlers to elements.
    32.cloneNode()It duplicates a node, including it's attributes and child nodes.
    33.appendChild()This method is used to add a new child node(element) as the last child node of the specified parent node.
    34.compareDocumentPosition()It enables understanding of document structure by comparing the positions of two DOM elements(nodes) and returns a bitmask(numeric value).
    35.focus()This method sets focus to specific webpage elements.
    36.getAttributeNode()It is used to get the attribute node object.
    37.getBoundingClientRect()This method is used to get the size of an element and its position relative to the viewport.
    38.getElementsByClassName()This method retrieves a live HTMLCollection of elements that match a specified class name within a document or a specific element.
    39.getElementsByTagName()It retrieves a live HTMLCollection of elements that match a specified tag name.
    40.insertAdjacentText()It allows you to insert a text content at a specific position relative to the element that calls this method.

    List of JavaScript DOM Element Properties

    The table given below contains a list of JavaScript DOM element properties −

    Sr.NoProperties & Description
    1.titleIt helps us to access and update the value stored in an element's title attribute.
    2.textContentThis property is used to access and update the text content of an HTML element and all its child elements as a single string.
    3.tagNameIt gives you the name of the HTML tag in uppercase that defines an element on a webpage.
    4.styleUsing this property, you can get the CSS styles that are directly set for a particular element.
    5.tabIndexIt is used to access and update the value of the tabIndex attribute for an element.
    6.scrollLeftThis property is used to access and update how far an element's content is scrolled horizontally.
    7.scrollTopIt is used to access and update how far an element's content is scrolled vertically.
    8.scrollWidthThis property gives you the total horizontal width of an element's content in pixels.
    9.scrollHeightYou can get the total vertical height of an element's content in pixels using this property.
    10.idThe id property is used for setting and retrieving the value of the element's id attribute.
    11.innerTextIt allows us to retrieve or change the visible text content directly within an HTML element on a web page.
    12.isContentEditableIt is used to check if a webpage element can be edited by users directly.
    13.langThe lang property is an attribute of an HTML element that specifies the language code.
    14.lastChildThe lastChild property returns a node that points to the last child node of a specific parent element.
    15.lastElementChildIt returns a node that holds the last child element of a parent element.
    16.namespaceURIThe namespaceURI property of an element provides the namespace URI assigned to the element.
    17.nextElementSiblingUsing this property, you can get the immediate next node in the sequence of a particular element.
    18.nextSiblingIt is used to access the immediate next node in sequence from the current node within the DOM tree.
    19.nodeNameThis property is used to identify a node's type and name based on its content.
    20.nodeTypeThe nodeType Property returns an integer value representing the type of a node.
    21.nodeValueIt is used for accessing and updating the value of a node.
    22.offsetHeightThis property is used to get the complete visible height of that element on the webpage, including both its vertical padding and borders, measured in pixels.
    23.offsetLeftIt returns the pixel based measurement of the distance from the element's left boundary to its nearest positioned parent's left boundary.
    24.offsetParentIt is used to find the closest ancestor element that affects the positioning of another element.
    25.offsetWidthThe offsetWidth property of an element gives you the total visible width of that element on the webpage.
    26.outerHTMLThe outerHTML property fetches the entire HTML code of an element.
    27.outerTextThis property can access or update the text content of an HTML element, including all its nested text and elements.
    28.ownerDocumentIt gives you the object for the document node that contains a specific element.
    29.parentElementIt allows you to access the immediate parent element of a particular element within the HTML element.
    30.parentNodeThis property is used to access the immediate parent node of a particular node within the HTML element.
    31.classListIt acts as an active container that holds a collection of CSS classes assigned to an element's class attribute.
    32.childNodesIt is used to retrieve all child nodes of an element, including elements, text nodes, and comments.
    33.classNameYou can access or modify the value of the class attribute of an element using this property.
    34.clientTopIt is used to get the accurate element positioning and size calculation in webpage layouts.
    35.firstElementChildIt provides the first child element within a given parent element.
    36.offsetTopUsing this property, you can get the pixel-based vertical distance from the element's top edge of its nearest positioned ancestor's top edge.
    37.attributesIt returns 'NameNodeMap' containing the collection of attributes of an HTML element
    38.accesskeyThis property allows you to assign a keyboard shortcut to an element on a webpage.
    39.firstChildIt helps you to access the very first child node of a given parent element in the HTML DOM.
    40.innerHTMLThis property allows us to read the existing HTML content of an element and update it with new HTML content.
    41.dirIt provides access for setting and retrieving the value of dir attributes of any element in HTML.
    42.contentEditableYou can make text content inside the HTML elements editable using this property.
    43.clientWidthIt returns the width of an element, including padding but excluding margin, border, or scrollbar width.
    44.clientLeftThis property is used to get the width of an element's left border, excluding left padding or margin.
    45.clientHeightIt is used to get the inner height of an element, including padding but not margin, border, or scrollbar width.
    46.childrenThis property returns a collection of child elements.
    47.childElementCountIt returns the count of direct child elements of a specified element.