Blog

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

  • DOM Document

    JavaScript DOM Document

    The JavaScript DOM document object owns all objects in the webpage. It represents the webpage. When the webpage is loaded in the web browser, it creates an HTML DOM ‘document’ object. It is the root of the HTML document.

    The DOM document object contains the various properties and methods you can use to get details about HTML elements and customize them. With document objects, JavaScript can access, and change document’s structure, content or style.

    To access any HTML element, you should always start accessing with the DOM document object.

    Accessing DOM Document Object

    The webpage is represented as the DOM document object. If we want to access any element in the webpage, we need to first start accessing the document object. In JavaScript, the document object is a property of the window object. So we can access the document object as a property of window object using window.document syntax. We can also access it without writing window.

    window.document
    

    or simply

    document
    

    This interactive example will help you understand the working of document.getElementById() method.

    Window Document Object

    The URL Property

    Extract URL

    JavaScript DOM Document Methods

    List of JavaScript DOM document methods are −

    Sr.NoMethod & Description
    1.writeln()This method provides the functionality to write HTML or JavaScript expressions directly to a document. It adds a newline character after each statement.
    2.write()This method provides the functionality to write HTML or JavaScript expressions directly to a document.
    3.hasFocus()It is used for determining if the document or any element inside the document has focus or not.
    4.renameNode()It is used to rename the nodes.
    5.open()This method opens a document for writing.
    6.normalizeDocument()This method normalize an entire HTML document.
    7.normalize()It removes empty text nodes, and joins adjacent text nodes from parent node.
    8.adoptNode()This method adopts a node from another document into the current document.
    9.addEventListener()It is used to set up a function that will be called whenever the specified event is delivered to the target.
    10.execCommand()This method is used for executing a command specified on the editable section that is being selected by the user.
    11.createTextNode()It is used to create a text node with the specified text.
    12.createEvent()It is used for creating an event object whose event type is specified in the parameter.
    13.createDocumentFragment()It creates a new empty document fragment which resides in memory.
    14.createComment()This method is used for creating a comment node with the given text.
    15.createAttribute()It is used to create an attribute with a specific name using JavaScript for an HTML element and return the Attr object.
    16.close()It closes the output stream.
    20.getElementsByTagName()It is a read-only method which is used to get the collection of all the elements in the document having the specified tag name in parameter.
    21.getElementsByName()This method is used to return collection of elements with the name attribute specified in the parameter.
    22.getElementsByClassName()This method is used for getting the collection of all the elements in the document with specified class name.
    23.getElementById()It returns the element of the given ID.
    24.createElement()This method creates an HTML element specified by tag name or element name.

    JavaScript DOM Document Properties

    In the following table, we have listed JavaScript DOM document properties −

    Sr.NoProperties & Description
    1.URLIt is a read-only property which returns the complete URL of the document including the protocol.
    2.titleThis property is used to set or get the title of the document.
    3.strictErrorCheckingIt is used to determine whether document enforce strict error checking or not.
    4.scriptsIt is a read-only property used for returning all the script elements present within HTML document as a collection.
    5.linksThe links is a read-only property which returns a collection of all the links corresponding to a and area elements with href attribute.
    6.lastModifiedThis property returns the date and time of the current document when it was last modified.
    7.inputEncodingThe inputEncoding property returns a String which represents the documents character encoding.
    8.implementationThis returns a DOMImplementation object which is associated with the current document.
    9.imagesIt is a read-only property used for returning all the img elements present within HTML document as a collection.
    10.headThe head property returns the HTML head element.
    11.formsThe forms is a read-only property used for returning all the form elements present within HTML document as a collection.
    12.embedsIt is a read-only property which returns all the embed elements present within HTML document as a collection.
    13.domConfigThis property is deprecated due to which will return undefined in all new browsers.
    14.domainIt is used for getting the domain name of the server on which the document is currently being executed.
    15.documentURIThis property is used to set or return the document’s location.
    16.documentModeThe documentMode property is an IE8 property which determines the rendering mode used by browser.
    17.documentElementIt returns the documentElement as an Element Object.
    18.doctypeThis property returns the DTD (Document Type Declaration) that are associated with the current HTML document.
    19.designModeIt helps us to determine if the entire document is editable or not.
    20.defaultViewIt is used for returning document’s window object.
    21.cookieThe HTML DOM document cookie property is used for creating, reading and deleting cookies.
    22.charsetIt returns the character encoding of the HTML document.
    23.appletsIt is used to return a list of all the applets elements within a document but this property is now deprecated.
    24.characterSetThis property is used to get character encoding of the document.
    25.anchorsThe anchors property is a read only property which lists all the “a” tag with name attribute in the document.
    26.baseURIIt is used to return the base Uniform Resource Identifier (URI) of the document.

    Here, we have explained some properties of the HTML DOM ‘document’ object with examples in JavaScript.

    Document childElementCount Property

    In JavaScript, the childElementCount property of the document object returns the count of the child elements of the document.

    Syntax

    Follow the syntax below to use the childElementCount property of document object in JavaScript.

    document.childElementCount;

    Example

    In the below code, the childElementCount property returns 1, as the document contains only 1 child element,. Other HTML elements are the child of the body.

    <html><body><div>First Element</div><div>Second Element</div><div>Third Element</div><div id ="output"></div><script>
    
      document.getElementById('output').innerHTML ="Total number of child elements in the document is: "+ document.childElementCount;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    First Element
    Second Element
    Third Element
    Total number of child elements in the document is: 1
    

    Document Links Property

    The Document Links property returns the collection of all links of the document. After that, you can use the for...of loop to traverse the collection of links.

    Syntax

    Follow the syntax below to use the document 'links' property in JavaScript.

    document.links;

    Example

    In the below code, the web page contains the two <a> elements. We access their href attribute's value using the links property.

    After that, we used the for...of loop to traverse the collection of links and print them on the web page.

    <html><body><div><a href ="https://tutorialspoint.com/"> Home </a></div><div><a href ="https://www.tutorialspoint.com/articles/category/javascript"> JavaScript </a></div><div id ="output"></div><script>const allLinks = document.links;
    
      document.getElementById("output").innerHTML +="The webpage contains the below links. &lt;br&gt;";for(let link of allLinks){
         output.innerHTML += link +"&lt;br&gt;";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Home
    JavaScript
    The webpage contains the below links.
    https://tutorialspoint.com/
    https://www.tutorialspoint.com/articles/category/javascript
    

    Document Title Property

    In JavaScript, the DOM document title property returns the title of the web page.

    Syntax

    Follow the syntax below to access the DOM document title of the web page.

    document.title;

    Example

    In the below code, we have added the <title> tag in the <head> tag.

    After that, we used the 'title' property of the document to access the web page's title.

    <html><head><title> JavaScript -HTMLDOM Document </title></head><body><div id ="output">The title of the document is:</div><script>
    
      document.getElementById("output").innerHTML += document.title;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The title of the document is: JavaScript - HTML DOM Document

  • DOM Methods & Properties

    In JavaScript, DOM methods are used to perform a particular action on HTML elements. The DOM represents a HTML document or web page with a logical tree. In the tree, each branch ends in a node, and each node contains objects. DOM methods allow us programmatic access to the tree. Using the DOM methods, you can change the document’s structurestyle, or content.

    For example, you can use DOM methods to access HTML elements using id, attribute, tag name, class name, etc., add events to the document or HTML elements, add new HTML elements to the DOM, etc.

    Syntax

    Following is the syntax to access and execute the DOM method in JavaScript −

    window.document.methodName();OR
    document.methodName();

    You may or may not use the ‘window’ object to access the document object’s method.

    Here, we have explained some HTML DOM methods with examples and covered other methods in the reference.

    JavaScript document.getElementById() Method

    The JavaScript getElementById() method of the document object is the most popular method to access the HTML elements using the id.

    Syntax

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

    const ele = document.getElementById("id");

    The getElementById() method takes an id of the HTML element as a parameter.

    Example

    In the below code, the id of the ‘div’ element is ‘output’.

    In JavaScript, we use the document.getElementById() method to access the div element using its id.

    Also, we use the ‘innerHTML’ property of the element to add extra HTML to the ‘div’ element.

    <html><body><button onclick ="accessEle()"> Access output and write </button><p id ="output"></p><script>functionaccessEle(){
    
         document.getElementById("output").innerHTML ="Hello User! You have just clicked the button!";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    JavaScript document.addEventListener() Method

    The addEventListener() method is used to add the event to the document.

    Syntax

    Follow the syntax below to use the addEventListener() method with a document.

    document.addEventListener('mouseover',function(){// Perform action on the document.});

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

    Example

    In the below code, we added the 'mouseover' event to the document. Whenever you hover over the document, it will change the background color of the document body to red.

    <html><body><h3>JavaScript  document.addEventListener() Method </h3><p> Hover over here to change background color </p><script>
    
      document.addEventListener('mouseover',function(){
         document.body.style.backgroundColor ='red';});&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    JavaScript document.write() Method

    The document.write() method adds the text or HTML to the document. It replaces the content of the document with the HTML passed as an argument of the method.

    Syntax

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

    document.write(HTML)

    You can replace the 'HTML' argument with the text or HTML.

    Example

    In the below code, we execute the writeText() function when you click the button.

    In the function, we use the document.write() method to add HTML to the web page. It replaces the HTML of the whole web page.

    <html><body><button onclick ="writeText()"> Add HTML</button><script>functionwriteText(){
    
         document.write("&lt;p&gt;Hello Users, Text is written using the document.write() method. &lt;/p&gt;");}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    List of DOM Methods

    In the below table, we have listed all methods related to the HTML DOM −

    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.
    41.namedItem()It is used to get the first element of collection whose id or name matches with the name mentioned in parameter.
    42.item()It returns the element from the HTMLCollection located at specified index in parameter.
    43.entries()This method retrieves an iterator, that allows us to iterate through all the key/value pairs in the object.
    44.forEach()This method calls the callback function mentioned in the parameter once for each value pair in the list in the order of their insertion.
    45.item()This method retrieves a node from the NodeList specified by the index in the parameter.
    46.keys()This method retrieves an iterator that allows us to go through all the keys contained in the NodeList.
    47.writeln()This method provides the functionality to write HTML or JavaScript expressions directly to a document. It adds a newline character after each statement.
    48.write()This method provides the functionality to write HTML or JavaScript expressions directly to a document.
    49.hasFocus()It is used for determining if the document or any element inside the document has focus or not.
    50.renameNode()It is used to rename the nodes.
    51.open()This method opens a document for writing.
    52.normalizeDocument()This method normalize an entire HTML document.
    53.normalize()It removes empty text nodes, and joins adjacent text nodes from parent node.
    54.adoptNode()This method adopts a node from another document into the current document.
    55.addEventListener()It is used to set up a function that will be called whenever the specified event is delivered to the target.
    56.execCommand()This method is used for executing a command specified on the editable section that is being selected by the user.
    57.createTextNode()It is used to create a text node with the specified text.
    58.createEvent()It is used for creating an event object whose event type is specified in the parameter.
    59.createDocumentFragment()It creates a new empty document fragment which resides in memory.
    60.createComment()This method is used for creating a comment node with the given text.
    61.createAttribute()It is used to create an attribute with a specific name using JavaScript for an HTML element and return the Attr object.
    62.close()It closes the output stream.
    63.getElementsByTagName()It is a read-only method which is used to get the collection of all the elements in the document having the specified tag name in parameter.
    64.getElementsByName()This method is used to return collection of elements with the name attribute specified in the parameter.
    65.getElementsByClassName()This method is used for getting the collection of all the elements in the document with specified class name.
    66.getElementById()It returns the element of the given ID.
    67.createElement()This method creates an HTML element specified by tag name or element name.
    68.add()This method adds one or more tokens specified in the parameter to the DOMTokenList.
    69.contains()This method checks whether the list contains the specified token, and returns a boolean value accordingly.
    70.entries()This method returns an iterator that is allowing to go through all the key/value pairs.
    71.forEach()This method calls the callback function mentioned in the parameter once for each value pair in the list in the order of their insertion.
    72.item()This method returns a token from the DOMTokenList specified by the index in the parameter.
    73.keys()This method returns an iterator which allows you to go through all the keys contained in the token list.
    74.remove()This method removes one or more tokens specified in the parameter to the DOMTokenList.
    75.replace()This method replaces the existing token in DomTokenList with a new token specified in the parameter.
    76.supports()This method checks whether the token specified in the parameter is supported in DOMTokenList.
    77.toggle()This method dynamically adds or removes a token or class from an element class attribute.
    78.values()This method returns an iterator allowing us to go through all values contained in the token list.

    List of DOM Properties

    The below table shows all properties related to the HTML DOM −

    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.
    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.
    48.srcThis property used for elements like <img>, <script>, or <iframe> to get or set the source URL.
    49.hrefThis property is used for anchor <a> elements to get or set the hyperlink reference.
    50.checkedThis property is used to get or set the checked state of a checkbox or radio button.
    51.disabledThis property is used to get or set the disabled state of an input element.
    52.lengthIt returns the number of elements in an HTMLCollection.
    53.lengthThis method returns the number of items in the NodeList.
    54.valueThis property is used to set or get the value of an attribute.
    55.specifiedIt checks whether the mentioned attribute is specified or not.
    56.nameIt is used get the name of the used attribute on an element.
    57.isIdThis property determines whether a HTML attribute is an 'id' attribute or not.
    58.URLIt is a read-only property which returns the complete URL of the document including the protocol.
    59.titleThis property is used to set or get the title of the document.
    60.strictErrorCheckingIt is used to determine whether document enforce strict error checking or not.
    61.scriptsIt is a read-only property used for returning all the script elements present within HTML document as a collection.
    62.linksThe links is a read-only property which returns a collection of all the links corresponding to a and area elements with href attribute.
    63.lastModifiedThis property returns the date and time of the current document when it was last modified.
    64.inputEncodingThe inputEncoding property returns a String which represents the documents character encoding.
    65.implementationThis returns a DOMImplementation object which is associated with the current document.
    66.imagesIt is a read-only property used for returning all the img elements present within HTML document as a collection.
    67.headThe head property returns the HTML head element.
    68.formsThe forms is a read-only property used for returning all the form elements present within HTML document as a collection.
    69.embedsIt is a read-only property which returns all the embed elements present within HTML document as a collection.
    70.domConfigThis property is deprecated due to which will return undefined in all new browsers.
    71.documentURIThis property is used to set or return the document's location.
    72.documentModeThe documentMode property is an IE8 property which determines the rendering mode used by browser.
    73.documentElementIt returns the documentElement as an Element Object.
    74.doctypeThis property returns the DTD (Document Type Declaration) that are associated with the current HTML document.
    75.designModeIt helps us to determine if the entire document is editable or not.
    76.defaultViewIt is used for returning document's window object.
    77.cookieThe HTML DOM document cookie property is used for creating, reading and deleting cookies.
    78.charsetIt returns the character encoding of the HTML document.
    79.appletsIt is used to return a list of all the applets elements within a document but this property is now deprecated.
    80.characterSetThis property is used to get character encoding of the document.
    81.anchorsThe anchors property is a read only property which lists all the "a" tag with name attribute in the document.
    82.baseURIIt is used to return the base Uniform Resource Identifier (URI) of the document.
    83.lengthThis method returns the number of tokens in a token list.
    84.valueThis method returns the DOMTokenList serialized as a string.
    85.domainIt is used for getting the domain name of the server on which the document is currently being executed.
  • Document Object Model 

    The HTML DOM allows JavaScript to access and modify the content of HTML elements. JavaScript can change all HTML elements, attributes, CSS styles in the page. JavaScript can also add, remove the HTML elements and attributes. Using JavaScript, we can even create new events in the page.

    Every web page resides inside a browser window which can be considered as an object.

    A Document object represents the HTML document that is displayed in that window. The Document object has various properties that refer to other objects which allow access to and modification of document content.

    What is DOM?

    The DOM is an acronym for the Document Object Model. It is a programming interface for Core, XML, and HTML DOM.

    It is a W3C (World Wide Web Consortium) standard.

    The DOM defines the logical or tree-like structure of the web page or document. In the tree, each branch ends in a node, and each node contains objects. DOM methods allow us programmatic access to the tree. Using the DOM methods, you can change the document’s structure, content or style.

    What is HTML DOM?

    HTML creates the web page’s structure, and JavaScript adds interaction to the web page by manipulating the HTML elements.

    JavaScript cant interact directly with HTML elements. So, whenever a web page loads in the browser, it creates a DOM.

    So, the document object represents the HTML document displayed in that window. Furthermore, each iframe in the webpage creates a new DOM. The Document object has various properties that refer to other objects that allow access to and modify document content.

    The way a document content is accessed and modified is called the Document Object Model, or DOM. The Objects are organized in a hierarchy. This hierarchical structure applies to the organization of objects in a Web document.

    • Window object − It represents the current window of the browser. It also works as a global object for the browser window. It is at the top of the hierarchy. It is the outmost element of the object hierarchy.
    • Document object − Each HTML document that gets loaded into a window becomes a document object. The document contains the contents of the page. It is used to access and modify the elements of the web page.
    • Form object − Everything enclosed in the <form>…</form> tags sets the form object.
    • Form control elements − The form object contains all the elements defined for that object, such as text fields, buttons, radio buttons, and checkboxes.

    Here is a simple hierarchy of a few important objects −

    HTML DOM

    There are several DOMs in existence. The following sections explain each of these DOMs in detail and describe how you can use them to access and modify document content.

    • The Legacy DOM − This is the model which was introduced in early versions of JavaScript language. It is well supported by all browsers, but allows access only to certain key portions of documents, such as forms, form elements, and images.
    • The W3C DOM − This document object model allows access and modification of all document content and is standardized by the World Wide Web Consortium (W3C). This model is supported by almost all the modern browsers.

    There are three different types of the DOM according to the W3C.

    • Core DOM − It is a standard model for all document types.
    • HTML DOM − It is a standard model for HTML documents.
    • XML DOM − It is a standard model for XML documents.

    Why is DOM required?

    As discussed above, when a web page is loaded into the browser window, it becomes a document object.

    After that, JavaScript can access the HTML elements and perform the other operations on them. It means JavaScript can interact with the web page using the HTML DOM.

    For example, JavaScript can perform the below operations on HTML elements using the document object.

    • Access HTML elements
    • Replace HTML elements
    • Add New HTML elements
    • Delete HTML elements
    • Change CSS of HTML elements
    • Change attributes of HTML elements
    • Add animation to HTML elements
    • Add events to HTML elements

    However, there are other uses of the document object, which we will cover in upcoming chapters.

    DOM Interfaces

    The DOM interfaces are the actual components of the DOM that work with JavaScript or any other programming language to manipulate the web page. They provide various methods and properties to interact with and manipulate web pages.

    List of the DOM interfaces is −

    • DOMTokenList
    • NodeList
    • HTMLCollection
    • Element
    • Document
    • Attribute (attr)
  • var Keyword

    The var keyword in JavaScript is used to declare variables. Before ES6, there was only var keyword to declare a variable. In ES6, let and const keywords were introduced as a better way to declare variables. It is advised to use let instead of var to declare a variable. If you are targeting older version of browser, you can use var.

    In JavaScript, variables are the data storage container. You can use the variables to store any type of data. For example, string, number, boolean, object, etc.

    A variable declared with var keyword has function scope. Whereas a variable declared with let has block scope.

    Syntax

    Follow the syntax below to define the variable using the ‘var’ keyword.

    var identifier;var identifier = value;

    Here, the identifier can be a valid variable name. In the JavaScript – Variables chapter, we have already discussed the rules to define valid identifiers.

    You may assign or not value to the variable while declaring it using the JavaScript ‘var’ keyword.

    Example

    In the below code, we have defined the 3 variables using the ‘var’ keyword. In the num1 variable, we have stored the numeric value. In the str1 variable, we have stored the string value; in the bool variable, we have stored the boolean value.

    <html><body><div id ="output1"></div><div id ="output2"></div><div id ="output3"></div><script>var num1 =30;var str1 ="Hello World!";var bool =true;
    
      document.getElementById('output1').innerHTML = num1;
      document.getElementById('output2').innerHTML = str1;
      document.getElementById('output3').innerHTML = bool;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    30
    Hello World!
    true
    

    JavaScript Variable Scopes

    The scope of the variable defined using the JavaScript 'var' keyword has a function scope or global scope.

    JavaScript Function Scope

    When you define the variable inside the function using the var keyword, it can be accessible inside the function anywhere. Even if you define the variable using the var keyword inside the particular block inside the function, it can be accessible anywhere.

    Let's understand the function scope with the example below.

    Example

    In the below code, we have defined the variable 'x' inside the function. We have also defined the variable 'y' inside the block, which is inside the function.

    After that, we access the variables x and y inside the function.

    <html><body><div id ="demo1"></div><div id ="demo2"></div><script>functiondemo(){var x =10;{var y =20;// x and y both can be accessible here}
    
         document.getElementById('demo1').innerHTML ="X == "+ x;
         document.getElementById('demo2').innerHTML ="Y == "+ y;}demo();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    X == 10
    Y == 20
    

    If you define the variable using the let keyword inside the block, which is inside the function, and try to access it outside the block, it will throw an error.

    JavaScript Global Scope

    It becomes the global variable if you define the variable using the 'var' keyword outside the function or a particular block.

    After that, you can access the variable anywhere inside the code using the window object.

    Example

    We have defined the 'num1' global variable in the code below.

    After that, we access the 'num1' variable inside the function using and without using the window object.

    <html><body><div id ="output"></div><script>const output = document.getElementById('output');var num1 =10;functionsum(num2){
    
         output.innerHTML +="num1 + num2 = "+(num1 + num2)+"&lt;br&gt;";
         output.innerHTML +="window.num1 + num2 = "+(window.num1 + num2);}sum(20);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    num1 + num2 = 30
    window.num1 + num2 = 30
    

    JavaScript Variable Hoisting

    The variable defined using the 'var' keyword is hoisted at the top of its scope. It means JavaScript adds the declaration of the variable at the top of its scope.

    So you can access the variable before the declaration of the variable.

    Example

    In the below code, we have initialized the variable 'a' and printed its value before its declaration.

    The code runs without error, as the variable defined using the var keyword is hoisted at the top of its scope.

    <html><body><div id ="output">Value of the variable a is:</div><script>functioncheckHoisting(){
    
         a =98;
         document.getElementById('output').innerHTML += a;var a;}// You can't access the variable a here.checkHoisting();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Value of the variable a is: 98
    

    The above JavaScript code is similar to the below code.

    var a;
    a =98;
    document.getElementById('output').innerHTML += a;

    Redeclaration of variable defined using the 'var' keyword

    You can redeclare the variables using the 'var' keyword, and the code will run without any error.

    If you have initialized the last duplicate variable with the latest value, it will contain that value. But if you don't initialize the last duplicate variable, the variable will contain its previous value without losing it.

    Example

    In the code below, we have defined the variable 'a' two times and initialized it with different values. You can observe in the output that variable 'a' contains the last value.

    We have defined the variable 'a' a third time and haven't initialized it. So, it contains the value of the 2nd 'a' variable.

    <html><body><div id ="demo"></div><script>const output = document.getElementById('demo');var a =10;var a =20;
    
      output.innerHTML +="The value of the a is: "+ a +"&lt;br&gt;";var a;
      output.innerHTML +="The value of the a is: "+ a;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The value of the a is: 20
    The value of the a is: 20
    

    If you define the duplicate variables in the different scopes, it can have value according to where you access the variable.

    Example

    In the code below, we have defined the 'num' variable outside and inside the function. When you access it inside or outside the function, it prints the different values.

    <html><body><div id ="demo"></div><script>const output = document.getElementById('demo');var num =10;functionprintNum(){var num =20;
    
         output.innerHTML +="Num inside the function is: "+ num +"&lt;br&gt;";}printNum();
      output.innerHTML +="Num outside the function is: "+ num +"&lt;br&gt;";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Num inside the function is: 20
    Num outside the function is: 10
    

    Declaring Many Variables in a Single Statement

    If you want to declare multiple variables using the JavaScript 'var' keyword, you can declare all variables in a single statement. It makes code readable.

    Example

    In the below code, we have declared the variables 'a' and 'b' in the single statement and initialized them with different values after declaring.

    <html><body><div id ="output1"></div><div id ="output2"></div><script>var a, b;
    
      a =70;
      b =80;
      document.getElementById('output1').innerHTML ="The value of a is: "+ a;
      document.getElementById('output2').innerHTML ="The value of b is: "+ b;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The value of a is: 70
    The value of b is: 80
    

    However, you can also assign the values to the variables while declaring the multiple variables in a single statement.

    Using the var keyword with loops

    When you use the JavaScript 'var' keyword to define the iterator variable of for loop, you can also access it outside the for loop.

    Example

    In the below code, we have defined the variable 'p' inside the for loop. We access the variable p inside and outside the loop.

    <html><body><div id ="output"></div><script>const output = document.getElementById('output');for(var p =0; p <5; p++){
    
         output.innerHTML +="The value of p is: "+ p +"&lt;br&gt;";}
      output.innerHTML +="The value of p outside the loop is: "+ p;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The value of p is: 0
    The value of p is: 1
    The value of p is: 2
    The value of p is: 3
    The value of p is: 4
    The value of p outside the loop is: 5
    

    Declaration with Destructuring

    In JavaScript, you can declare the variables using the 'var' keyword while destructuring the array or objects.

    Example

    In the below code, the 'arr' array contains 3 variables.

    After that, we define variables using the 'var' keyword and destructure the array.

    <html><body><div id ="output"></div><script>const output = document.getElementById('output');var arr =[4,5,6];var[a, b, c]= arr;
    
      output.innerHTML ="a = "+ a +", b = "+ b +", c = "+ c;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    a = 4, b = 5, c = 6
    

    You can also use the 'var' keyword to define the variables and store the objects or function expressions.

  • new Keyword

    The new keyword in JavaScript is used to create an instance of the object that has constructor function. Using new keyword, we can create the instances of a user-defined as well as built-in object types. We can create instances of the classes, prototype, or constructor functions.

    When a JavaScript function is called with new keyword, the function is used as constructor. The new keyword will do the following:

    • Creates a blank/ empty JavaScript object.
    • Sets its prototype for inheritance.
    • Binds this variable internally with newly created object.
    • Executes the constructor function using new crated object whenever this is used.
    • Returns newly created object, unless the contractor function returns a non-null object reference.

    The new keyword is also used to create an instance of the built-in JavaScript objects like String, Boolean, Number, etc.

    Syntax

    The syntax to use the new keyword in JavaScript is as follows

    newConstructor(arguments);

    Parameters

    • Constructor − It is the name of the constructor function or class name.
    • arguments −It can be multiple arguments to initialize the object properties with them.

    Return Value

    • It returns the newly created object if the constructor function returns nothing or a primitive value.
    • It returns the value that is returned by constructor function if constructor returns a non-primitive value.

    Using ‘new’ keyword with Function Constructor

    To use a function as a constructor, we should call the function with new keyword placing it before the function name.

    We can define multiple objects using function constructor. The function constructor works as the object’s prototype.

    Follow the syntax below to use the ‘new’ keyword and constructor function to define the object.

    newFuncName(arguments);

    Example

    We have defined the Watch() constructor function in the code below.

    The Watch() constructor function initializes the brand, price, and type properties.

    After that, we have created two new instances of the Watch() function and printed them in the output.

    <html><body><div id ="output"></div><script>functionWatch(brand, price, type){this.brand = brand;this.price = price;this.type = type;}const titan =newWatch('titen',4000,'analog');const sonata =newWatch('sonata',3000,'digital');
       document.getElementById('output').innerHTML +="The titan object is: "+JSON.stringify(titan)+"<br>"+"The sonata object is: "+JSON.stringify(sonata);</script></body></html>

    Output

    The titan object is: {"brand":"titen","price":4000,"type":"analog"}
    The sonata object is: {"brand":"sonata","price":3000,"type":"digital"}
    

    Example

    In the below code, we have defined the Laptop() constructor function, initializing various properties related to the laptop. Also, we have defined the getLaptop() function, which prints the laptop details.

    After that, we created the two instances of the Laptop() object and used the getLaptop() method with both. In this way, you can share single methods with different objects.

    <html><body><div id ="output"></div><script>const output = document.getElementById('output');functionLaptop(brand, model, processor){this.brand = brand;this.model = model;this.processor = processor;this.getLaptop=function(){
    
         output.innerHTML +=this.brand +", "+this.model +", "+this.processor +"&lt;br&gt;";}}constHP=newLaptop('HP',"VIKING","i7");const Dell =newLaptop('Dell',"Inspiron","i5");HP.getLaptop();
    Dell.getLaptop();</script></body></html>

    Output

    HP, VIKING, i7
    Dell, Inspiron, i5
    

    Using ‘new’ keyword with Class

    You can also use the new keyword to define the instance of a class. The class also provides the blueprint for the object.

    Before ES6, the constructor function was used to define the template for the object. After ES6, classes are used to define the template for the object.

    Example

    In the below example, we have defined the ‘WindowClass class. In the ‘WindowClass’ we have added the constructor to initialize the properties. We have also added the getDetails() method in the class.

    After that, we used the ‘new’ keyword followed by the class name to define an object of the WindowClass.

    Next, we invoke the getDetails() method on the instance of the class.

    <html><body><div id ="demo"></div><script>const output = document.getElementById('demo')classWindowClass{constructor(color, size, type){this.color = color;this.size = size;this.type = type;}getDetails=function(){
    
            output.innerHTML ="Color: "+this.color +"&lt;br&gt;"+"Size: "+this.size +"&lt;br&gt;"+"Type: "+this.type;}}// Creating the instance of WindowClass classconst window1 =newWindowClass('blue','small','wooden');// Calling function object
      window1.getDetails();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Color: blue
    Size: small
    Type: wooden
    

    Using 'new' keyword with built-in object

    You can also use the 'new' keyword to define the instance of the built-in object having constructor functions.

    Follow the syntax below to create an instance of the built-in object Number.

    const num =newNumber(10);

    In the above syntax, we have passed the numeric value as an argument of the Number() constructor.

    Example

    In the code below, we have used the Number() and String() constructors with a new keyword to define the numeric and string objects.

    After that, we used the 'typeof' operator to check the type of num and str variables. In the output, you can see that the num and str variable type is an object.

    <html><body><div id ="output"></div><script>const num =newNumber(10);const str =newString("Hello");
    
      document.getElementById("output").innerHTML ="num = "+ num +", typeof num "+typeof num +"&lt;br&gt;"+"str = "+ str +", typeof str "+typeof str;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    num = 10, typeof num object
    str = Hello, typeof str object

  • void Keyword

    The void keyword in JavaScript is used as an operator that evaluates a given expression and returns undefined. The void is an important keyword in JavaScript. The meaning of the void is null or empty.

    The void keyword can be used as a unary operator that appears before its single operand, which may be of any type. This operator specifies an expression to be evaluated without returning a value or returning the undefined.

    Syntax

    The syntax to use the void keyword in JavaScript −

    void operand;

    In the above syntax, the operand can be any expression.

    Return Value

    It returns the undefined.

    Example

    In the below code, we used the 10 with the ‘void’ keyword. In the output, you can observe that it returns undefined.

    <html><body><div id ="output">The value of the ans variable is:</div><script>let ans =void10;
    
      document.getElementById("output").innerHTML += ans;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The value of the ans variable is: undefined
    

    Importance of Precedence of void Keyword

    Generally, the JavaScript 'void' keyword is used to return the primitive undefined value, but if you don't take precedence in the consideration, it can return a different value.

    Let's understand it via the example below.

    Example

    In the below code, the void operator takes precedence over the strict equality operator in the first expression. So, it first evaluates 'void 10' to undefined and compares it with 20. So, it returns false.

    The second expression evaluates '10 === 20' first to false and evaluates 'void false' to undefined.

    <html><body><div id ="output1"></div><div id ="output2"></div><script>let res1 =void10===20;let res2 =void(10===20);
    
      document.getElementById("output1").innerHTML += res1;
      document.getElementById("output2").innerHTML += res2;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    false
    undefined
    

    What is javascript:void(0)?

    Let's break down the javascript:void(0) into two parts and understand both separately.

    javascript:

    You can use the 'javascript:' to create a pseudo URL. Using 'javascript:' you can create the interactive URL.

    You need to write the expression after 'javascript:', and when users click the anchor text, it executes the JavaScript code.

    Let's understand it via the example below.

    Example

    In the below code, we have created the link text and used the JavaScript URL as a href. When you click the anchor text, it writes it in the HTML document.

    <html><body><a href ="javascript:document.write('Anchor text is clicked!')"> Click me!</a></body></html>

    In this way, you can use the 'javascript:uri' to create the pseudo URL.

    void(0)

    The void(0) evaluates the JavaScript expression, but it returns undefined. So, when you want to execute the expression without performing any action, you can use the void(0).

    javascript: void(0)

    When you don't want to navigate users to another web page when they click on the link, you can use the 'javascript:void(0)' as a href value of the anchor tag.

    Let's understand it via the example below.

    Example

    It won't do anything Whenever you click the anchor text in the code below.

    <html><body><a href ="javascript:void(0)"> Click me!</a></body></html>

    You can also use the 'javascript:void(0)' when you want to update the web page using the URI but don't want to navigate to another web page.

    Example

    In the below code, when you click the anchor text, it will change the background color of the body, rather than navigating to another web page.

    <html><body><a href ="javascript:void(0);" 
    
       	  onclick ="document.body.style.backgroundColor = 'blue'"&gt; 
       	  Change Background Color 
    </a></body></html>

    The void Keyword with Functions

    When you use the void keyword with JavaScript functions, it returns undefined. After that, if you try to execute the function, it will throw an error, as the 'void' operator considers the function as its operand and evaluates it as undefined.

    Example

    In the below code, we have defined the test() function and used the 'void' keyword with it.

    Also, used the trycatch block to catch the error.

    In the try block, we execute the function, and in the output, you can observe that control goes into the catch block.

    <html><body><div id ="demo"></div><script>const output = document.getElementById('demo');try{voidfunctiontest(){
    
         output.innerHTML +="The test function is executed!";}test();}catch(error){
      output.innerHTML +="The test function is undefined!";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The test function is undefined!
    

    The void Keyword with Immediately Invoked Function

    When you use the 'void' keyword with the JavaScript immediately invoked function, it invokes the function expression first and evaluates it as undefined.

    Example

    In the below code, we have defined the immediately invoked function with the void keyword. You can observe that it invokes the function first and returns undefined.

    <html><body><div id ="demo"></div><script>const output = document.getElementById("demo");voidfunction(){
    
         output.innerHTML ="Unknown function is executed!";}();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Unknown function is executed!
    

    Also, you can use the 'void' keyword with the arrow function to return undefined from the arrow function. The JavaScript:void() URI can also be used to prevent the web page reloading by default, like the preventDefault() method.

  • this Keyword

    What is ‘this’ keyword?

    In JavaScript, the ‘this‘ keyword contains the reference to the object. It represents the context of the function or current code. It is used to access the properties and methods of the current object.

    When this keyword is used inside a function, the this will refer to the object that the function is called with.

    In JavaScript, functions are also objects. So, you can use the ‘this’ keyword with functions also.

    Which object does the ‘this’ refer to?

    The object referred by the ‘this‘ keyword depends on how you have used the ‘this’ keyword.

    For example,

    • The ‘this’ keyword refers to the window object in the global scope.
    • When you use the ‘this’ keyword inside the function, it also represents the ‘window’ object.
    • The ‘this’ keyword refers to an undefined in the strict mode in the function.
    • The ‘this’ keyword refers to the object when you use it in the object method.
    • In the event handler, the ‘this‘ keyword refers to the element on which the event is executed.
    • The ‘this’ keyword in methods like call(), apply(), and bind() can refer to different objects.

    Syntax

    Follow the syntax below to use the ‘this’ keyword in JavaScript &minus

    this.property
    ORthis.method();

    You can access the properties and execute the object’s methods using the ‘this’ keyword.

    JavaScript ‘this’ in the Global Scope

    When you use the ‘this’ keyword in the global scope, it represents the global (window) object. You can access the global variables using the ‘this’ keyword in the global scope.

    Example

    In the below code, we have defined the ‘num’ variable and printNum() function in the global scope. After that, we used the ‘this’ keyword to access the global variable and functions.

    <html><body><div id ="demo"></div><script>const output = document.getElementById('demo');var num =10;functionprintNum(){
    
         output.innerHTML +="Inside the function: "+ num +"&lt;br&gt;";}this.printNum();
      output.innerHTML +="Outside the function: "+this.num +"&lt;br&gt;";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Inside the function: 10
    Outside the function: 10
    

    JavaScript 'this' in a Function

    When you use the 'this' keyword in the function, it represents the global scope or 'window' object.

    Example

    In the below code, we use the 'this' keyword inside the function. You can observe that we access the global variables using the 'this' keyword inside the function.

    <html><body><div id ="demo"></div><script>const output = document.getElementById('demo');var message ="Hello World!";functionprintMessage(){var message ="Hi! How are you?";
    
         output.innerHTML ="The messsage is: "+this.message;}printMessage();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The messsage is: Hello World!
    

    'this' in a Function in Strict Mode

    When you use the 'this' keyword inside the function in the strict mode, it doesn't refer to any object. The value of the 'this' keyword becomes undefined.

    Example

    In the below code, we use the 'this' keyword inside the function in the strict mode. It prints undefined.

    <html><body><div id ="demo"></div><script>let output = document.getElementById('demo');var message ="Hello World!";functiontest(){"use strict";
    
         output.innerHTML ="The value of this in the strict mode is: "+this;}test();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The value of this in the strict mode is: undefined
    

    'this' in a Constructor Function

    When you use the function as a constructor function to create an object, the 'this' keyword refers to the object.

    Example

    We have defined the Animal() constructor function in the code below. We used the 'this' keyword inside the constructor function to initialize the properties of the object.

    <html><body><div id ="demo"></div><script>const output = document.getElementById('demo');functionAnimal(){this.name ='Lion';this.age =3;this.color ='Brown';}const newAnimal =newAnimal();
    
      output.innerHTML ="Animal Name: "+ newAnimal.name +"&lt;br&gt;";
      output.innerHTML +="Animal Age: "+ newAnimal.age +"&lt;br&gt;";
      output.innerHTML +="Animal Color: "+ newAnimal.color;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Animal Name: Lion
    Animal Age: 3
    Animal Color: Brown
    

    'this' in an Arrow Function

    When you use the 'this' keyword in the arrow function, it refers to the scope of its parent object.

    For example, when you define the arrow function inside the object method and use the 'this' keyword inside that, it presents the object. The 'this' keyword refers to the global object if you define the arrow function inside another function.

    Example

    In the below code, we have defined the arrow function inside the getDetails() method of the object. When we print the value of the 'this' keyword, it prints the object.

    <html><body><div id ="output1">Value of'this' inside the getDetails() method:</div><div id ="output2">Value of'this' inside the getInnerDetails() method:</div><script>const wall ={
    		 size:"10",
    		 color:"blue",getDetails(){
    
    	    document.getElementById('output1').innerHTML +=JSON.stringify(this);constgetInnerDetails=()=&gt;{
    		   document.getElementById('output2').innerHTML +=JSON.stringify(this);}getInnerDetails();}}
      wall.getDetails();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Value of 'this' inside the getDetails() method: {"size":"10","color":"blue"}
    Value of 'this' inside the getInnerDetails() method: {"size":"10","color":"blue"}
    

    'this' in the Object Method

    When you use the 'this' keyword inside the object method, it represents the object itself.

    Example

    In the below code, we have defined the 'fruit; object. The object contains the printFruitDetails() method, and in the method, we used the 'this' keyword to access the properties of the object.

    <html><body><div id ="demo"></div><script>const output = document.getElementById('demo');const fruit ={
    
         name:"Apple",
         color:"red",printFruitDetails(){
            output.innerHTML +="Furit Name = "+this.name +"&lt;br&gt;";
            output.innerHTML +="Fruit Color = "+this.color;}}
      fruit.printFruitDetails();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Furit Name = Apple
    Fruit Color = red
    

    'this' in a Child Function of an Object Method

    When you define the function inside the object method and use the 'this' keyword inside the function, it represents the global object rather than an object.

    Example:

    In the below code, we have defined the person object. The person object contains the printDetails() method. In the printDetails() method, we have defined the printThis() function.

    In the printThis() function, we print the value of the 'this' keyword, and it prints the global object.

    <html><body><div id ="output">Inside the printThis()function, Value of'this'=</div><script>const person ={
    
      name:"Salman",
      isBusinessman:false,printDetails(){functionprintThis(){
            document.getElementById('output').innerHTML +=this;}printThis();}}
    person.printDetails();</script></body></html>

    Output

    Inside the printThis() function, Value of 'this' = [object Window]
    

    JavaScript 'this' in Event Handlers

    Using the 'this' keyword with event handlers refers to the HTML element on which the event is executed.

    Example

    In the below code, we have added the onClick event handler into the <div> element. When users click the div element, we hide the div element using the 'display' property.

    <html><head><style>
    
      div {
        height:200px;
        width:700px;
        background-color: red;}&lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;p&gt;Click the DIV below to remove it.&lt;/p&gt;&lt;div onclick ="this.style.display = 'none'"&gt;&lt;/div&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Explicit Function Binding in JavaScript

    In JavaScript, call(), apply(), or bind() methods are used for the explicit binding.

    The explicit binding allows you to borrow the method of the particular object. Using these methods, you can explicitly define the context of the 'this' keyword.

    Let's understand explicit binding using the examples below.

    Example: Using the call() method

    In the below code, the lion object contains the color and age property. It also contains the printDetails() method and prints the details using the 'this' keyword.

    The tiger object contains only color and age properties. We used the call() method to call the printDetails() method of the lion object with the context of the tiger object. So, the method prints the details of the tiger in the output.

    <html><body><div id ="demo"></div><script>const output = document.getElementById('demo');const lion ={
    
    color:"Yellow",
    age:10,printDetails(){
      output.innerHTML +=&amp;lt;p&amp;gt;Color: ${this.color}&amp;lt;/p&amp;gt;;
      output.innerHTML +=&amp;lt;p&amp;gt;Age: ${this.age}&amp;lt;/p&amp;gt;;}}const tiger ={
    color:"Orange",
    age:15,}
    lion.printDetails.call(tiger);</script></body></html>

    Output

    Color: Orange
    
    Age: 15
    

    Example: Using the bind() method

    The below code also contains the lion and tiger objects. After that, we used the bind() method to bind the printDetails() method of the lion object into the tiger object.

    After that, we use the tigerDetails() method to print the details of the tiger object.

    <html><body><div id ="demo"></div><script>const output = document.getElementById('demo');const lion ={
    
    color:"Yellow",
    age:10,printDetails(){
      output.innerHTML +=&amp;lt;p&amp;gt;Color: ${this.color}&amp;lt;/p&amp;gt;;
      output.innerHTML +=&amp;lt;p&amp;gt;Age: ${this.age}&amp;lt;/p&amp;gt;;}}const tiger ={
    color:"Orange",
    age:15,}const tigerDetails = lion.printDetails.bind(tiger);tigerDetails();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Color: Orange
    
    Age: 15
    

    JavaScript 'this' Precedence

    You should use the below precedence order to determine the context of the 'this' keyword.

    • 1. bind() method
    • 2. call and apply() methods
    • 3. Object method
    • 4. Global scope