Category: Miscellaneous

  • Web RTC

    Web RTC introduced by World Wide Web Consortium (W3C) that supports browser-to-browser applications for voice calling, video chat, and P2P file sharing.

    The web RTC implements three API’s as shown below −

    • MediaStream − get access to the user’s camera and microphone.
    • RTCPeerConnection − get access to audio or video calling facility.
    • RTCDataChannel − get access to peer-to-peer communication.

    MediaStream

    The MediaStream represents synchronized streams of media, For an example, Click on HTML5 Video player in HTML5 demo section or else click here.

    The above example contains stream.getAudioTracks() and stream.VideoTracks(). If there is no audio tracks, it returns an empty array and it will check video stream,if webcam connected, stream.getVideoTracks() returns an array of one MediaStreamTrack representing the stream from the webcam. A simple example is chat applications, a chat application gets stream from web camera, rear camera, microphone.

    Sample code of MediaStream

    function gotStream(stream) {
       window.AudioContext = window.AudioContext || window.webkitAudioContext;
       var audioContext = new AudioContext();
       
       // Create an AudioNode from the stream
       var mediaStreamSource = audioContext.createMediaStreamSource(stream);
       // Connect it to destination to hear yourself
       // or any other node for processing!
       mediaStreamSource.connect(audioContext.destination);
    }
    navigator.getUserMedia({audio:true}, gotStream);
    

    Session Control, Network & Media Information

    Web RTC required peer-to-peer communication between browsers. This mechanism required signaling, network information, session control and media information. Web developers can choose different mechanism to communicate between the browsers such as SIP or XMPP or any two way communications.

    Sample code of createSignalingChannel()

    var signalingChannel = createSignalingChannel();
    var pc;
    var configuration = ...;
    // run start(true) to initiate a call
    function start(isCaller) {
       pc = new RTCPeerConnection(configuration);
       // send any ice candidates to the other peer
       pc.onicecandidate = function (evt) {
    
      signalingChannel.send(JSON.stringify({ "candidate": evt.candidate }));
    }; // once remote stream arrives, show it in the remote video element pc.onaddstream = function (evt) {
      remoteView.src = URL.createObjectURL(evt.stream);
    }; // get the local stream, show it in the local video element and send it navigator.getUserMedia({ "audio": true, "video": true }, function (stream) {
      selfView.src = URL.createObjectURL(stream);
      pc.addStream(stream);
      if (isCaller)
         pc.createOffer(gotDescription);
      else
         pc.createAnswer(pc.remoteDescription, gotDescription);
         function gotDescription(desc) {
            pc.setLocalDescription(desc);
            signalingChannel.send(JSON.stringify({ "sdp": desc }));
         }
      });
    } signalingChannel.onmessage = function (evt) {
      if (!pc)
         start(false);
         var signal = JSON.parse(evt.data);
      if (signal.sdp)
         pc.setRemoteDescription(new RTCSessionDescription(signal.sdp));
      else
         pc.addIceCandidate(new RTCIceCandidate(signal.candidate));
    };
  • CORS

    Cross-origin resource sharing (CORS) is a mechanism to allows to load the restricted resources from another domain in web browser

    For example, suppose we click on HTML5 video player in HTML5 demo section. First, it will ask camera permission, if user allow the permission then only it will open the camera otherwise not.

    Making a CORS request

    The modern browsers like Chrome, Firefox, Opera and Safari all use the XMLHttprequest2 object and Internet Explorer uses the similar XDomainRequest object.

    function createCORSRequest(method, url) {
       var xhr = new XMLHttpRequest();
       
       if ("withCredentials" in xhr) {
    
      // Check if the XMLHttpRequest object has a "withCredentials" property.
      // "withCredentials" only exists on XMLHTTPRequest2 objects.
      xhr.open(method, url, true);
    } else if (typeof XDomainRequest != "undefined") {
      // Otherwise, check if XDomainRequest.
      // XDomainRequest only exists in IE, and is IE's way of making CORS requests.
      xhr = new XDomainRequest();
      xhr.open(method, url);
    } else {
      // Otherwise, CORS is not supported by the browser.
      xhr = null;
    } return xhr; } var xhr = createCORSRequest('GET', url); if (!xhr) { throw new Error('CORS not supported'); }

    Event handles in CORS

    Sr.No.Event Handler & Description
    1onloadstartStarts the request
    2onprogressLoads the data and send the data
    3onabortAbort the request
    4onerrorrequest has failed
    5onloadrequest load successfully
    6ontimeouttime out has happened before request could complete
    7onloadendWhen the request is complete either successful or failure

    Example of onload or onerror event

    xhr.onload = function() {
       var responseText = xhr.responseText;
       // process the response.
       console.log(responseText);
    };
    xhr.onerror = function() {
       console.log('There was an error!');
    };
    

    Example of CORS with handler

    Below example will show the example of makeCorsRequest() and onload handler

    // Create the XHR object.
    function createCORSRequest(method, url) {
       var xhr = new XMLHttpRequest();
       if ("withCredentials" in xhr) {
    
      
      // XHR for Chrome/Firefox/Opera/Safari.
      xhr.open(method, url, true);
    } else if (typeof XDomainRequest != "undefined") {
      
      // XDomainRequest for IE.
      xhr = new XDomainRequest();
      xhr.open(method, url);
    } else {
      
      // CORS not supported.
      xhr = null;
    } return xhr; } // Helper method to parse the title tag from the response. function getTitle(text) { return text.match('<title>(.*)?</title>')[1]; } // Make the actual CORS request. function makeCorsRequest() { // All HTML5 Rocks properties support CORS. var url = 'http://www.tutorialspoint.com'; var xhr = createCORSRequest('GET', url); if (!xhr) {
      alert('CORS not supported');
      return;
    } // Response handlers. xhr.onload = function() {
      var text = xhr.responseText;
      var title = getTitle(text);
      alert('Response from CORS request to ' + url + ': ' + title);
    }; xhr.onerror = function() {
      alert('Woops, there was an error making the request.');
    }; xhr.send(); }
  • Web Messaging

    Web Messaging is the way for documents to separates browsing context to share the data without Dom. It overrides the cross domain communication problem in different domains, protocols or ports.

    For example, if we want to send the data from our page to ad container which is placed at iframe or voice-versa, in this scenario, Browser throws a security exception. With web messaging we can pass the data across as a message event.

    Message Event

    Message events fires Cross-document messaging, channel messaging, server-sent events and web sockets. It is described by Message Event interface.

    Properties of Message Event

    The following table contains a list of Message Event properties −

    S.No.Property & Description
    1dataContains string data
    2originContains Domain name and port
    3lastEventIdContains unique identifier for the current message event.
    4sourceContains to A reference to the originating documents window
    5portsContains the data which is sent by any message port

    Sending a cross-document message

    Before send cross document message, we need to create a new web browsing context either by creating new iframe or new window. We can send the data using with postMessage() and it has two arguments. They are as

    • message − The message to send
    • targetOrigin − Origin name

    Examples

    Sending message from iframe to button

    var iframe = document.querySelector('iframe');
    var button = document.querySelector('button');
    var clickHandler = function(){
       iframe.contentWindow.postMessage('The message to send.','https://www.tutorialspoint.com);
    }
    button.addEventListener('click',clickHandler,false);
    

    Receiving a cross-document message in the receiving document

    var messageEventHandler = function(event){
       // check that the origin is one we want.
       if(event.origin == 'https://www.tutorialspoint.com'){
    
      alert(event.data);
    } } window.addEventListener('message', messageEventHandler,false);

    Channel messaging

    Two-way communication between the browsing contexts is called channel messaging. It is useful for communication across multiple origins.

    The MessageChannel and MessagePort Objects

    While creating messageChannel, it internally creates two ports to sending the data and forwarded to another browsing context.

    • postMessage() − Post the message throw channel
    • start() − It sends the data
    • close() − it close the ports

    In this scenario, we are sending the data from one iframe to another iframe. Here we are invoking the data in function and passing the data to DOM.

    var loadHandler = function(){
       var mc, portMessageHandler;
       mc = new MessageChannel();
       window.parent.postMessage('documentAHasLoaded','http://foo.example',[mc.port2]);
       portMessageHandler = function(portMsgEvent){
    
      alert( portMsgEvent.data );
    } mc.port1.addEventListener('message', portMessageHandler, false); mc.port1.start(); } window.addEventListener('DOMContentLoaded', loadHandler, false);

    Above code, it is taking the data from port 2, now it will pass the data to second iframe

    var loadHandler = function(){
       var iframes, messageHandler;
       iframes = window.frames;
       messageHandler = function(messageEvent){
    
      if( messageEvent.ports.length &gt; 0 ){
         // transfer the port to iframe[1]
         iframes[1].postMessage('portopen','http://foo.example',messageEvent.ports);
      }
    } window.addEventListener('message',messageHandler,false); } window.addEventListener('DOMContentLoaded',loadHandler,false);

    Now second document handles the data by using the portMsgHandler function.

    var loadHandler(){
       // Define our message handler function
       var messageHandler = function(messageEvent){
    
      
      // Our form submission handler
      var formHandler = function(){
         var msg = 'add &lt;[email protected]&gt; to game circle.';
         messageEvent.ports[0].postMessage(msg);
      }
      document.forms[0].addEventListener('submit',formHandler,false);
    } window.addEventListener('message',messageHandler,false); } window.addEventListener('DOMContentLoaded',loadHandler,false);
  • IndexedDB

    The indexedDB is a new HTML5 concept to store the data inside user’s browser. It is more powerful than local storage and useful for applications that requires to store large amount of the data. These applications can run more efficiency and load faster.

    Why to use indexedDB?

    The W3C has announced that the Web SQL database is a deprecated local storage specification so web developer should not use this technology any more. The indexedDB is an alternative for web SQL data base and more effective than older technologies.

    Features

    • It stores key-pair values
    • It is not a relational database
    • IndexedDB API is mostly asynchronous
    • It is not a structured query language
    • It allows to access the data from same domain

    IndexedDB

    Before enter into an indexedDB, we need to add some prefixes of implementation as shown below −

    window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
    
    window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction;
    window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange
    
    if (!window.indexedDB) {
       window.alert("Your browser doesn't support a stable version of IndexedDB.")
    }
    

    Open an IndexedDB database

    Before creating a database, we have to prepare some data for the data base.let’s start with company employee details.

    const employeeData = [
       { id: "01", name: "Gopal K Varma", age: 35, email: "[email protected]" },
       { id: "02", name: "Prasad", age: 24, email: "[email protected]" }
    ];
    

    Adding the data

    Here adding some data manually into the data as shown below −

    function add() {
       var request = db.transaction(["employee"], "readwrite")
       .objectStore("employee")
       .add({ id: "01", name: "prasad", age: 24, email: "[email protected]" });
       
       request.onsuccess = function(event) {
    
      alert("Prasad has been added to your database.");
    }; request.onerror = function(event) {
      alert("Unable to add data\r\nPrasad is already exist in your database! ");
    } }

    Retrieving Data

    We can retrieve the data from the data base using with get()

    function read() {
       var transaction = db.transaction(["employee"]);
       var objectStore = transaction.objectStore("employee");
       var request = objectStore.get("00-03");
       
       request.onerror = function(event) {
    
      alert("Unable to retrieve daa from database!");
    }; request.onsuccess = function(event) {
      if(request.result) {
         alert("Name: " + request.result.name + ", Age: " + request.result.age + ", Email: " + request.result.email);
      } else {
         alert("Kenny couldn't be found in your database!");
      }
    }; }

    Using with get(), we can store the data in object instead of that we can store the data in cursor and we can retrieve the data from cursor

    function readAll() {
       var objectStore = db.transaction("employee").objectStore("employee");
       
       objectStore.openCursor().onsuccess = function(event) {
    
      var cursor = event.target.result;
      
      if (cursor) {
         alert("Name for id " + cursor.key + " is " + cursor.value.name + ", Age: " + cursor.value.age + ", Email: " + cursor.value.email);
         cursor.continue();
      } else {
         alert("No more entries!");
      }
    }; }

    Removing the data

    We can remove the data from IndexedDB with using the remove() method. Here is how the code looks like −

    function remove() {
       var request = db.transaction(["employee"], "readwrite")
       .objectStore("employee")
       .delete("02");
       
       request.onsuccess = function(event) {
    
      alert("prasad entry has been removed from your database.");
    }; }

    HTML Code

    To show all the data we need to use onClick event as shown below code −

    <!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>IndexedDb Demo | onlyWebPro.com</title></head><body><button onclick="read()">Read </button><button onclick="readAll()"></button><button onclick="add()"></button><button onclick="remove()">Delete </button></body></html>

    The final code should be as −

    <!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><script type="text/javascript">
    
      
      //prefixes of implementation that we want to test
      window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
      
      //prefixes of window.IDB objects
      window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction;
      window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange
      
      if (!window.indexedDB) {
         window.alert("Your browser doesn't support a stable version of IndexedDB.")
      }
      
      const employeeData = [
         { id: "00-01", name: "gopal", age: 35, email: "[email protected]" },
         { id: "00-02", name: "prasad", age: 32, email: "[email protected]" }
      ];
      var db;
      var request = window.indexedDB.open("newDatabase", 1);
      
      request.onerror = function(event) {
         console.log("error: ");
      };
      
      request.onsuccess = function(event) {
         db = request.result;
         console.log("success: "+ db);
      };
      
      request.onupgradeneeded = function(event) {
         var db = event.target.result;
         var objectStore = db.createObjectStore("employee", {keyPath: "id"});
         
         for (var i in employeeData) {
            objectStore.add(employeeData[i]);
         }
      }
      function read() {
         var transaction = db.transaction(["employee"]);
         var objectStore = transaction.objectStore("employee");
         var request = objectStore.get("00-03");
         
         request.onerror = function(event) {
            alert("Unable to retrieve daa from database!");
         };
         request.onsuccess = function(event) {
            
            // Do something with the request.result!
            if(request.result) {
               alert("Name: " + request.result.name + ", Age: " + request.result.age + ", Email: " + request.result.email);
            } else {
               alert("Kenny couldn't be found in your database!");
            }
         };
      }
      
      function readAll() {
         var objectStore = db.transaction("employee").objectStore("employee");
         objectStore.openCursor().onsuccess = function(event) {
            var cursor = event.target.result;
            
            if (cursor) {
               alert("Name for id " + cursor.key + " is " + cursor.value.name + ", Age: " + cursor.value.age + ", Email: " + cursor.value.email);
               cursor.continue();
            } else {
               alert("No more entries!");
            }
         };
      }
      
      function add() {
         var request = db.transaction(["employee"], "readwrite")
         .objectStore("employee")
         .add({ id: "00-03", name: "Kenny", age: 19, email: "[email protected]" });
         
         request.onsuccess = function(event) {
            alert("Kenny has been added to your database.");
         };
         request.onerror = function(event) {
            alert("Unable to add data\r\nKenny is aready exist in your database! ");
         }
      }
      
      function remove() {
         var request = db.transaction(["employee"], "readwrite")
         .objectStore("employee")
         .delete("00-03");
         
         request.onsuccess = function(event) {
            alert("Kenny's entry has been removed from your database.");
         };
      }
    </script></head><body><button onclick="read()">Read </button><button onclick="readAll()">Read all </button><button onclick="add()">Add data </button><button onclick="remove()">Delete data </button></body></html>

  • Microdata

    Microdata is a standardized way to provide additional semantics in the web pages. It lets us define our own customized elements and start embedding custom properties in the web pages. The microdata consists of a group of name-value pairs.

    The groups are called items, and each name-value pair is a property. Items and properties are represented by regular elements.

    Using Microdata in HTML document

    Earlier, we mentioned that the microdata has group of name-value pairs (property) and this group is known as items.

    • To create an item, the itemscope attribute is used.
    • To add a property to an item, the itemprop attribute is used on one of the item’s descendants.

    Example

    In this example, there are two items, each of which has the property “name” −

    <html><body><div itemscope><p>My name is <span itemprop="name">Zara</span>.</p></div><div itemscope><p>My name is <span itemprop="name">Nuha</span>.</p></div></body></html>

    Properties generally have values that are strings but it can have following data types −

    Global Attributes

    Microdata introduces five global attributes which would be available for any element to use and give context for machines about your data.

    S.No.Attribute & Description
    1itemscopeThis is used to create an item. The itemscope attribute is a Boolean attribute that tells that there is Microdata on this page, and this is where it starts.
    2itemtypeThis attribute is a valid URL which defines the item and provides the context for the properties.
    3itemidThis attribute is global identifier for the item.
    4itempropThis attribute defines a property of the item.
    5itemrefThis attribute gives a list of additional elements to crawl to find the name-value pairs of the item.

    Properties Datatypes

    Properties generally have values that are strings as mentioned in above example but they can also have values that are URLs. Following example has one property, “image”, whose value is a URL −

    <div itemscope><img itemprop="image" src="tp-logo.gif" alt="TutorialsPoint"></div>

    Properties can also have values that are dates, times, or dates and times. This is achieved using the time element and its datetime attribute.

    <html><body><div itemscope>
    
      My birthday is −
      &lt;time itemprop="birthday" datetime="1971-05-08"&gt;
         Aug 5th 1971
      &lt;/time&gt;&lt;/div&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Properties can also themselves be groups of name-value pairs, by putting the itemscope attribute on the element that declares the property.

    Microdata API support

    If a browser supports the HTML5 microdata API, there will be a getItems() function on the global document object. If browser doesn't support microdata, the getItems() function will be undefined.

    function supports_microdata_api() {
       return !!document.getItems;
    }
    

    Modernizr does not yet support checking for the microdata API, so we will need to use the function like the one listed above.

    The HTML5 microdata standard includes both HTML markup (primarily for search engines) and a set of DOM functions (primarily for browsers).

    We can include microdata markup in our web pages and the search engines that are not capable to understand the microdata attributes will just ignore them. But if we need to access or manipulate microdata through the DOM, we need to check whether the browser supports the microdata DOM API.

    Defining Microdata Vocabulary

    To define microdata vocabulary, you need a namespace URL which points to a working web page. For example, http://data-vocabulary.org/Person can be used as the namespace for a personal microdata vocabulary with the following named properties −

    • name − Person name as a simple string
    • Photo − A URL to a picture of the person.
    • URL − A website belonging to the person.

    Using about properties a person microdata could be as follows −

    <html><body><div itemscope><section itemscope itemtype="http://data-vocabulary.org/Person"><h1 itemprop="name">Gopal K Varma</h1><p><img itemprop="photo" src="http://www.tutorialspoint.com/green/images/logo.png"></p><a itemprop="url" href="#">Site</a></section></div></body></html>

    Google supports microdata as part of their Rich Snippets program. When Google's web crawler parses your page and finds microdata properties that conform to the vocabulary, it parses out those properties and stores them alongside the rest of the page data.

    For further development on Microdata you can always refer to HTML5 Microdata.

  • MathML

    HTML MathML (Mathematical Markup Language) is used to embed mathematical equations and chemical reaction equations into HTML document.

    Mathematical Markup Language (MathML)

    • Mathematical Markup Language is a XML based markup language introduced in 2015.
    • It helps to represent complex mathematical formula in human readable format.
    • This representation also helps software to understand context of the equation.
    • To embed MathML elements inside a web page, we can use the HTML <math> tag.

    HTML MathML Elements

    The following table contains a list of MathML elements used in HTML:

    ElementDescription
    <math>It is the top level tag (root) of all MathML elements.
    <mrow>It indicates row of a given table or matrix.
    <msqrt>It displays square roots symbol in an expression.
    <msub>It is used for adding subscript in a given expression.
    <msup>It is used for adding superscript in a given expression.
    <mo>It represents operators such as equal to, comma and so on.
    <mi>It represents identifiers such as variable or constant.
    <mtable>It is used for creating table or matrix.
    <mtr>It is used for table row or matrix row.
    <mtd>It is used to enter data in a cell of a table or a matrix.

    Purpose of HTML MathML

    MathML is helpful to display formula in technical and mathematical webpages. This ensures clear math content in e-learning materials, scientific papers and complex algorithms.

    MathML is only supported in Google Chrome and Mozilla Firefox browsers. Please make sure that your browser supports MathML before testing it.

    Examples MathML in HTML

    Following are some examples that illustrates how to use MathML elements in HTML.

    Pythagorean theorem Using MathML

    In this example, we will make Pythagorean Equation using HTML code.

    <!DOCTYPE html><html><head><meta charset="UTF-8"><title>Pythagorean theorem</title></head><body><math><mrow><msup><mi>a</mi><mn>2</mn></msup><mo>+</mo><msup><mi>b</mi><mn>2</mn></msup><mo>=</mo><msup><mi>c</mi><mn>2</mn></msup></mrow></math></body></html>

    Quadratic Equation using MathML

    In this example we will make a Quadratic Equation using HTML code.

    <!DOCTYPE html><html><head><title>MathML Examples</title></head><body><math><mrow><msup><mi>x</mi><mn>2</mn></msup><mo>+</mo><mn>4</mn><!-- Invisible times operator --><mo>⁢</mo><mi>x</mi><mo>+</mo><mn>4</mn><mo>=</mo><mn>0</mn></mrow></math></body></html>

    Make Matrix in MathML

    Consider the following example which would be used to represent a simple 2×2 matrix:

    <!DOCTYPE html><html><head><title>MathML Examples</title></head><body><math><mrow><mi>A</mi><mo>=</mo><mfenced open="[" close="]"><mtable><mtr><mtd><mi>x</mi></mtd><mtd><mi>y</mi></mtd></mtr><mtr><mtd><mi>z</mi></mtd><mtd><mi>w</mi></mtd></mtr></mtable></mfenced></mrow></math></body></html>

    Redox Equation in MathML

    Below is an example of a redox chemical equation using MathML.

    <!DOCTYPE html><html><head><title>MathML Examples</title></head><body><math><mrow><msub><mtext>Zn</mtext></msub><mo>+</mo><msub><mrow><mtext>CuSO</mtext><mn>4</mn></mrow></msub><!-- Arrow Symbol --><mo>→</mo><msub><mrow><mtext>ZnSO</mtext><mn>4</mn></mrow></msub><mo>+</mo><msub><mtext>Cu</mtext></msub></mrow></math></body></html>
  • Document Object Model

    HTML Document Object Model (DOM)

    The HTML Document Object Model (in short, HTML DOM) represents all the elements of an HTML document in a hierarchical order (or tree structure). Where each node of this tree represents an element in the HTML document.

    Accessing and Modifying HTML DOM

    Using the HTML DOM methods we can access the tree and modify the structure or, contents of the respective HTML document. We can also have events attached to the nodes.

    HTML DOM Tree Structure

    For instance, if your HTML document contains elements like <html><head><body><title><link><img> and <p>, the browser will create a DOM Tree of the HTML document that can be represented as shown in the diagram given below −

    HTML DOM

    Please note that each HTML document contain <html>, <head> and <body> tags. The root element is <html>, and <head> and <body> tags are its child element.

    What is Document Object Model?

    The Document Object Model (DOM) is a programming interface that works as a bridge between web pages and scripts or programming languages. It represents a web document (like an HTML or XML) as a tree of objects where each branch of the tree ends with a node, and each node contains objects.

    Click on the button given below to understand it properly. It will generate a DOM Tree.Create DOM Tree

    The DOM provides a set of methods that allow programming languages, such as JavaScript, to access the DOM tree. Using these methods, you can change the document’s structure, style, or content. It makes a web page interactive and dynamic.

    The DOM is not a programming language, it is designed to be language independent. Most web developers use the DOM through JavaScript, however, implementations of the DOM can be built for any language.

    HTML DOM vs JavaScript DOM

    We use HTML to structure a web page and JavaScript to make it interactive. However, JavaScript can not understand the a web page directly. It takes help of the HTML DOM. When an HTML page is loaded, the browser creates an Object Model of the page, which JavaScript can then interact with to manipulate the content, structure, and styles of the page.

    JavaScript can perform the below operations with the help of object model −

    • Access and replace HTML elements.
    • Access and replace HTML attributes.
    • Change all the CSS styles in the page.
    • Respond to user events.
    • Add animation to the web page.

    The below table explains the difference between HTML DOM and JavaScript DOM −

    HTML DOMJavaScript DOM
    The HTML DOM is an Object Model for HTML that represents all elements of an HTML document in a tree like structure.The HTML DOM is an API for JavaScript that helps add, change, and replace elements, attributes and events of an HTML document.

    DOM Methods Reference

    Below is a list of important DOM 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.

    Click here to view list of all methods….

    chevron

    DOM Properties Reference

    Below is a list of important DOM properties −

    Sr.NoMethod & 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.

    Click here to view list of all methods….

    chevron

    Frequently Asked Questions about DOM

    There are several Frequently Asked Questions(FAQ) about DOM, this section tries to answer some of them briefly.What is the full form of DOM?

    chevron

    Why DOM is used in JavaScript?

    chevron

    Is DOM a programming language?

    chevron

    What are DOM interfaces?

    chevron