JavaScript – HTML DOM

JavaScript – Document Object Model or DOM ”; Previous Next 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 can’t 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 − 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. Print Page Previous Next Advertisements ”;

JavaScript – Mouse Events

JavaScript – Mouse Events ”; Previous Next JavaScript mouse events allow users to control and interact with web pages using their mouse. These events trigger specific functions or actions in response to user clicks, scrolls, drags, and other mouse movements. To handle mouse events in JavaScript, you can use the addEventListener() method. The addEventListener() method takes two arguments: the event type and the event handler function. The event type is the name of the event that you want to handle, and the event handler function is the function that will be called when the event occurs. In web development, JavaScript provides a powerful mechanism to respond to user interactions with the mouse through a set of events. These events enable developers to create dynamic and interactive web applications by capturing and handling various mouse-related actions. Common Mouse Events Following are the most common JavaScript mouse events: Mouse Event Description Click When an element experiences the press of a mouse button, it triggers the click event. Double Click The dblclick event fires upon the rapid double-clicking of a mouse button. Mouse Down and Mouse Up The initiation of a mouse click triggers the ”mousedown” event, while the completion of that click causes the ”mouseup” event to occur. Mouse Move When the mouse pointer moves over an element, it triggers the ”mousemove” event; this event supplies developers with positional information about the mouse. This data empowers them to devise responsive interfaces that are rooted in dynamic mouse movements. Context Menu When the user attempts to open the context menu, typically by right-clicking, they trigger the contextmenu event. This event allows developers to customize or inhibit default behaviour of the context menu. Wheel When the mouse wheel rotates, it fires the ”wheel event”; this particular event commonly manifests in implementing features, notably zooming or scrolling. Drag and Drop Events like dragstart, dragend, dragover, dragenter, dragleave, and drop are associated with drag-and-drop functionality. They allow developers to create interactive interfaces for dragging elements within a web page. Example : Click Event In this example we demonstrate the click event. When the button is clicked, it prints an appropriate message to the console message i.e. “Clicked!”. This event is often used while submitting forms. <!DOCTYPE html> <html> <head> <title>Click Event Example</title> </head> <body> <button id=”clickButton”>Click me!</button> <p id = “output”></p> <script> const clickButton = document.getElementById(”clickButton”); const outputDiv = document.getElementById(“output”); clickButton.addEventListener(”click”, function(event) { outputDiv.innerHTML += ”Clicked!”+ JSON.stringify(event) + “<br>”; }); </script> </body> </html> Example: Double Click Event The dblclick event operates in this example, triggering upon a double-click of the designated button. We attach the event listener to an element with “doubleClickButton” as its id. A user”s double-click on the button prompts a function that logs a console message, confirming their interaction with it. <!DOCTYPE html> <html> <head> <title>Double Click Event Example</title> </head> <body> <button id=”doubleClickButton”>Double-click me!</button> <p id = “output”></p> <script> const doubleClickButton = document.getElementById(”doubleClickButton”); const outputDiv = document.getElementById(“output”); doubleClickButton.addEventListener(”dblclick”, function(event) { outputDiv.innerHTML += ”Double-clicked!” + JSON.stringify(event) + “<br>”; }); </script> </body> </html> Example: Mouse Down and Mouse Up Events The use of the mousedown and mouseup events is exemplified in this scenario: both events apply to a <div> element identified as “mouseUpDownDiv.” Two distinct event listeners are established; one responds to the down action of the mouse button, while another reacts upon release or up motion of said button. Upon pressing over the designated div (mousedown), a message indicating that the user has depressed their mouse button appears within your console log. When the user releases the mouse button (mouseup), we also log another message to indicate that the mouse button is up. <!DOCTYPE html> <html> <head> <title>Mouse Down and Mouse Up Events Example</title> </head> <body> <div id=”mouseUpDownDiv” style=”width: 600px; height: 100px; background-color: lightblue;”> Please perform mouse down and up event any where in this DIV. </div> <p id = “output”></p> <script> const mouseUpDownDiv = document.getElementById(”mouseUpDownDiv”); const outputDiv = document.getElementById(“output”); mouseUpDownDiv.addEventListener(”mousedown”, function(event) { outputDiv.innerHTML += ”Mouse button down!” + JSON.stringify(event) + “<br>”; }); mouseUpDownDiv.addEventListener(”mouseup”, function(event) { outputDiv.innerHTML += ”Mouse button up!” + JSON.stringify(event) + “<br>”; }); </script> </body> </html> Example: Mouse Move Event In this instance, we employ the mousemove event to monitor the mouse pointer”s movement over a specific <div> element identified as “mouseMoveDiv.” The handler function extracts clientX and clientY properties from an event object that represents X-Y coordinates of said pointer. Subsequently, these are logged into console; thus offering real-time feedback on where exactly within our designated div area is the user positioning their cursor. <!DOCTYPE html> <html> <head> <title>Mouse Move Event Example</title> </head> <body> <div id=”mouseMoveDiv” style=”width: 600px; height: 200px; background-color: lightgreen;”> Please move you mouse inside this DIV.</div> <p id = “output”></p> <script> const mouseMoveDiv = document.getElementById(”mouseMoveDiv”); const outputDiv = document.getElementById(“output”); mouseMoveDiv.addEventListener(”mousemove”, function(event) { const x = event.clientX; const y = event.clientY; outputDiv.innerHTML += `Mouse moved to (${x}, ${y})` + JSON.stringify(event) + “<br>”; }); </script> </body> </html> Example: Wheel Event This example showcases the wheel event, activated when the mouse wheel is rotated. The event listener is attached to a <div> element with the id “wheelDiv.” When the user rotates the mouse wheel over this div, the associated function logs a message to the console, indicating that the mouse wheel has been rotated. <!DOCTYPE html> <html> <head> <title>Wheel Event Example</title> </head> <body> <div id=”wheelDiv” style=”width: 600px; height: 200px; background-color: palevioletred;”> Please bring the curser inside this DIV and rotate the wheel of mouse.</div> <p id = “output”></p> <script> const wheelDiv = document.getElementById(”wheelDiv”); const outputDiv = document.getElementById(“output”); wheelDiv.addEventListener(”wheel”, function(event) { outputDiv.innerHTML += ”Mouse wheel rotated!”+ event + “<br>”; }); </script> </body> </html> Print Page Previous Next Advertisements ”;

JavaScript – DOM Forms

JavaScript – DOM Forms ”; Previous Next 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 Property Description length It represents the number of <form> elements in the HTML document. Methods of ”forms” Collection Method Description [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; </script> </body> </html> 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; </script> </body> </html> 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> function submitForm(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; } </script> </body> </html> 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> function submitForm(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 < 3 || lastname.length < 3) { output.innerHTML += “The length of the first name or last name should be greater than 3. <br>”; } else { output.innerHTML = “First Name: ” + firstname + “, Last Name: ” + lastname; } } </script> </body> </html> 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

JavaScript – DOM Methods

JavaScript – DOM Methods ”; Previous Next 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 structure, style, 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> function accessEle() { document.getElementById(“output”).innerHTML = “Hello User! You have just clicked the button!”; } </script> </body> </html> 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”; }); </script> </body> </html> 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> function writeText() { document.write(“<p>Hello Users, Text is written using the document.write() method. </p>”); } </script> </body> </html> List of DOM Methods In the below table, we have listed all methods related to the HTML DOM. You can access all methods using the ”document” object. Method Description addEventListener() It is used to add an event listener to the document. adoptNode() It is used to adopt the node from the other documents. append() It appends the new node or HTML after the last child node of the document. caretPositionFromPoint() It returns the caretPosition object, containing the DOM node based on the coordinates passed as an argument. close() It closes the output stream opened using the document.open() method. createAttribute() It creates a new attribute node. createAttributeNS() It creates a new attribute node with the particular namespace URI. createComment() It creates a new comment node with a specific text message. createDocumentFragment() It creates a DocumentFragment node. createElement() It creates a new element node to insert into the web page. createElementNS() It is used to create a new element node with a particular namespace URI. createEvent() It creates a new event node. createTextNode() It creates a new text node. elementFromPoint() It accesses the element from the specified coordinates. elementsFromPoint() It returns the array of elements that are at the specified coordinates. getAnimations() It returns the array of all animations applied on the document. getElementById() It accesses the HTML element using the id. getElementsByClassName() It accesses the HTML element using the class name. getElementsByName() It accesses the HTML element using the name. getElementsByTagName() It accesses the HTML element using the tag name. hasFocus() It returns the boolean value based on whether any element or document itself is in the focus. importNode() It is used to import the node from another document. normalize() It removes the text nodes, which are empty, and joins other nodes. open() It is used to open a new output stream. prepand() It is used to insert the particular node before all nodes. querySelector() It is used to select the first element that matches the css selector passed as an argument. querySelectorAll() It returns the nodelist of the HTML elements, which matches the multiple CSS selectors. removeEventListener() It is used to remove the event listener from the document. replaceChildren() It replaces the children nodes of the document. write() It is used to write text, HTML, etc., into the document. writeln() It is similar to the write() method but writes each statement in the new line. Print Page Previous Next Advertisements ”;

JavaScript – Changing CSS

JavaScript – Changing CSS ”; Previous Next Changing CSS with JavaScript JavaScript allows you to change the CSS of the HTML element dynamically. When HTML gets loaded in the browser, it creates a DOM tree. The DOM tree contains each HTML element in the object format. Furthermore, each HTML element object contains the ”style” object as a property. Here, a ”style” object contains various properties like color, backgroundcolor, etc., to change or get the element”s style. So, you can use various properties of the ”style” object to change the style of the particular HTML element. Syntax Follow the syntax below to change the CSS of the HTML element. element.style.property = value; In the above syntax, ”element” is an HTML element, which you need to access from the DOM tree. The ”property” is a CSS property, and the ”value” can be static or dynamic. Example: Changing the style of the HTML element We have applied the initial style to the div element in the code below. In JavaScript, we change the div element”s background color using the style object”s ”backgroundColor” property. <!DOCTYPE html> <html> <head> <style> div { background-color: blue; width: 700px; height: 100px; color: white; } </style> </head> <body> <div id = “square”> Changing the color of this Div. </div> <br> <button onclick=”changeColor()”> Change Color </button> <script> function changeColor() { let square = document.getElementById(”square”); square.style.backgroundColor = ”red”; } </script> </body> </html> Example: Adding multiple styles to a single HTML element In the below code, we change multiple CSS properties of the <div> element in the changeStyle() function. We use the ”backgroundColor’, ”color’, ”fontSize’, and ”width” properties to change the CSS. <!DOCTYPE html> <html> <body> <div id = “square”> Changing the style of this Div. </div> <br> <button onclick = “changeStyle()”> Change color </button> <script> function changeStyle() { document.getElementById(”square”).style.backgroundColor = ”red”; document.getElementById(”square”).style.color = “white”; document.getElementById(”square”).style.fontSize = “25px”; document.getElementById(”square”).style.width = “700px”; } </script> </body> </html> Changing Style of the Element When Event Triggers You can also change the style of the element when a particular event triggers. Example In the below code, we added the ”click” event to the <div> element. When users click the button, it changes the background color of the div element. <!DOCTYPE html> <html> <head> <style> div { width: 700px; height: 100px; color: white; background-color: orange; } </style> </head> <body> <div id = “square”> Click Me </div> <br> <script> const square = document.getElementById(”square”); square.addEventListener(”click”, () => { square.style.backgroundColor = ”green”; square.style.fontSize = “25px”; }); </script> </body> </html> Example In the below code, we added the ”hover” event on the div element. When the mouse cursor enters and leaves the div element, it changes the style of the div element. <!DOCTYPE html> <html> <head> <style> div { width: 700px; height: 100px; color: white; background-color: orange; } </style> </head> <body> <div id = “square”> Hover Me </div> <br> <script> const square = document.getElementById(”square”); square.addEventListener(”mouseenter”, () => { square.style.backgroundColor = ”green”; square.style.fontSize = “25px”; }); square.addEventListener(”mouseleave”, () => { square.style.backgroundColor = ”orange”; square.style.fontSize = “initial”; }); </script> </body> </html> Changing CSS of HTML elements Dynamically You can also change the CSS of the HTML element dynamically. You can assign values using the variables. Example We have added the default style to the <div> element in the code below. Also, we have created multiple radio buttons. When users select any radio button, it changes the style of the div element accordingly. <!DOCTYPE html> <html> <head> <style> p { width: 700px; height: 100px; color: white; background-color: blue; } </style> </head> <body> <div><p id = “square”>Select any of the following colors to change the background color</p></div> <div>Yellow: <input type = “radio” id = “yellow” name = “color”></div> <div>Green: <input type = “radio” id = “green” name = “color”></div> <div>Red: <input type = “radio” id = “red” name = “color”></div> <script> let square = document.getElementById(”square”); // Changing the style when radio button changes let colors = document.getElementsByName(”color”); for (let i = 0; i < colors.length; i++) { colors[i].addEventListener(”change”, function () { square.style.backgroundColor = this.id; }); } </script> </body> </html> Print Page Previous Next Advertisements ”;

JavaScript – Event Bubbling

JavaScript – Event Bubbling ”; Previous Next Event Bubbling Event bubbling is a concept in JavaScript that refers to the order in which events are handled as they propagate through the DOM (Document Object Model) hierarchy. When an event occurs on a particular element, such as a click or a keypress, it can trigger handlers not only on that specific element but also on its ancestors in the DOM tree. Event Bubbling Steps Here”s a step-by-step explanation of event bubbling − Event Triggering An event is triggered on a specific DOM element, like a button being clicked or a key being pressed. This is the starting point of the event propagation. Capturing Phase (optional) The event can optionally go through the capturing phase. This phase starts from the root of the DOM tree and moves towards the target element. During this phase, event handlers registered with the addEventListener method using the third parameter true will be executed. Target Phase The event reaches the target element, the one on which the event originally occurred. Bubbling Phase After the target phase, the event starts to bubble up from the target element towards the root of the DOM tree. During this phase, event handlers registered without the third parameter or with the third parameter set to false will be executed. Event Bubbling using 2 Nested DIVs In this example of nested <div> elements, event bubbling is evident as the click event on the child <div> propagates up through the DOM hierarchy to trigger the click event listener on the parent <div>. Despite being clicked on the child, both the child and parent event listeners respond to the click event sequentially. This behaviour showcases the default event bubbling mechanism in the DOM, where events traverse from the target element up to its ancestors, allowing multiple elements to respond to the same event. In the console, upon clicking the child <div>, the log messages for both the child and parent event listeners are displayed, illustrating the event bubbling process. <!DOCTYPE html> <html lang=”en”> <head> <style> .parent { width: 600px; height: 200px; background-color: #eee; position: relative; cursor: pointer; } .child { width: 400px; height: 100px; background-color: #66c2ff; position: absolute; top: 50px; left: 50px; } #message { margin-top: 10px; font-weight: bold; } </style> </head> <body> <h2>Nested Divs</h2> <div class=”parent” id=”parentDiv”> <div class=”child” id=”childDiv”>Click me!</div> </div> <div id=”message”></div> <script> let messageElement = document.getElementById(”message”); document.getElementById(”parentDiv”).addEventListener(”click”, function () { messageElement.innerHTML+=”Parent div clicked<br>”; }); document.getElementById(”childDiv”).addEventListener(”click”, function () { messageElement.innerHTML+=”Child div clicked<br>”; }); </script> </body> </html> The grey box is the parent div and blue box is the child div. Event Bubbling using 3 Nested Levels In this example with three nested levels of <div> elements, event bubbling is demonstrated as a click on the innermost Level 3 <div> triggers successive click event listeners on the parent Level 2 and Level 1 <div> elements. Styled with distinctive background colours, each level visually represents its hierarchy. Upon clicking the Level 3 <div>, the event propagates up, invoking event listeners for higher-level elements. Console logs reveal messages indicating the clicked level and its background colour, showcasing the streamlined event bubbling mechanism for handling nested structures in the DOM. <!DOCTYPE html> <html> <head> <style> .level1 { background-color: #ff9999; padding: 20px; text-align: center; max-width: 80%; cursor: pointer; } .level2 { background-color: #99ff99; padding: 15px; } .level3 { background-color: #9999ff; padding: 10px; cursor: pointer; } #message { margin-top: 10px; font-weight: lighter; border: 1px solid #ddd; padding: 10px; max-width: 80%; background-color: #f9f9f9; border-radius: 5px; font-family: ”Arial”, sans-serif; font-size: 14px; color: #333; } </style> </head> <body> <div class=”level1″ id=”div1″> Level 1 <div class=”level2″ id=”div2″> Level 2 <div class=”level3″ id=”div3″> Level 3 (Click me!) </div> </div> </div> <div id=”message”></div> <script> const messageElement = document.getElementById(“message”); document.getElementById(”div1”).addEventListener(“click”, function (event) { messageElement.innerHTML += “Clicked on Level 1, Background Color:” + getComputedStyle(event.target).backgroundColor + “<br>”; }); document.getElementById(”div2”).addEventListener(“click”, function (event) { messageElement.innerHTML += “Clicked on Level 2, Background Color:” + getComputedStyle(event.target).backgroundColor + “<br>”; }); document.getElementById(”div3”).addEventListener(”click”, function (event) { messageElement.innerHTML +=”Clicked on Level 3, Background Color:” + getComputedStyle(event.target).backgroundColor + “<br>”; }); </script> </body> </html> Print Page Previous Next Advertisements ”;

JavaScript – DOM Document

JavaScript – DOM Document ”; Previous Next HTML DOM Document The HTML 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 The DOM Document Properties The HTML DOM document object provides us with many properties that can be used to access and manipulate the HTML elements. Here, we have listed all properties of the document object. Property Description activeElement To get the currently focused element in the HTML document. adoptedStyleSheets It sets the array of the newly constructed stylesheets to the document. baseURI To get the absolute base URI of the document. body To set or get the document”s <body> tag. characterSet To get the character encoding for the document. childElementCount To get a count of the number of child elements of the document. children To get all children of the document. compatMode To get a boolean value representing whether the document is rendered in the standard modes. contentType It returns the MIME type of the document. cookie To get the cookies related to the document. currentScript It returns the script of the document whose code is currently executing. defaultView To get the window object associated with the document. designMode To change the editability of the document. dir To get the direction of the text of the document. doctype To get the document type declaration. documentElement To get the <html> element. documentURI To set or get the location of the document. embeds To get all embedded (<embed>) elements of the document. firstElementChild To get the first child element of the document. forms It returns an array of <form> elements of the document. fullScreenElement To get the element that is being presented in the full screen. fullScreenEnabled It returns the boolean value, indicating whether the full screen is enabled in the document. head It returns the <head> tag of the document. hidden It returns a boolean value, representing whether the document is considered hidden. images It returns the collection of the <img> elements. lastElementChild It returns the last child element of the document. lastModified To get the last modified date and time of the document. links To get the collection of all <a> and <area> elements. location To get the location of the document. readyState To get the current state of the document. referrer To get the URL of the document, which has opened the current document. scripts To get the collection of all <script> elements in the document. scrollingElement To get the reference to the element which scrolls the document. styleSheets It returns the style sheet list of the CSSStyleSheet object. timeLine It represents the default timeline of the document. title To set or get the title of the document. URL To get the full URL of the HTML document. visibilityState It returns the boolean value, representing the visibility status 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; </script> </body> </html> 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. <br>”; for (let link of allLinks) { output.innerHTML += link + “<br>”; } </script> </body> </html> 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 – HTML DOM Document </title> </head> <body> <div id = “output”>The title of the document is: </div> <script> document.getElementById(“output”).innerHTML += document.title; </script> </body> </html> Output The title of the document is: JavaScript – HTML DOM

JavaScript – Extending Errors

JavaScript – Extending Errors ”; Previous Next The custom errors in JavaScript are errors that you create yourself, as opposed to the built-in errors that JavaScript throws. You can create custom errors to handle specific types of errors that may occur in your code. To create a custom error, you can use the Error constructor. The Error constructor takes a string as its argument, which will be the message of the error. Extending the Error Class: Creating Custom Errors The best way to create custom errors is by creating a new class and extending it using the ”extends” keyword. It uses the concept of inheritance, and the custom error class inherits the properties of the Error class. In the constructor() function, you can initialize the properties of the custom error class. Syntax You can follow the syntax below to create custom errors by extending the Error class. class customError extends Error { constructor(message) { super(message) // Initialize properties } } In the above code, we call the parent class constructor using the super() method. You can also initialize the properties of the customError class in the constructor function. Example In the code below, we take the input from the user. When a user clicks the check age button, it calls the checkAge() function. We have defined the ageError class in JavaScript code and extended it with the Error class. In the ageError class, we have added the constructor() function to initialize the properties. In the constructor() function, we used the super() method to initialize the message property of the Error class. Also, we have initialized the ”name” and ”age” properties in the constructor function. In the checkAge() function, we throw the error if the age is less than 18, and in the catch{} block, we print the error message and age. <html> <body> <p>Enter your age: <input type = “number” id = “age” /> </p> <button onclick = “checkAge()”> Check Age </button> <p id = “demo”> </p> <script> const output = document.getElementById(“demo”); class ageError extends Error { constructor(message, age) { super(message); this.name = “ageError”; this.age = age // Custom property } } function checkAge() { const ageValue = document.getElementById(”age”).value; try { if (ageValue < 18) { // Throw error when age is less than 18 throw new ageError(“You are too young”, ageValue); } else { output.innerHTML = “You are old enough”; } } catch (e) { output.innerHTML = “Error: ” + e.message + “. <br>”; output.innerHTML += “Age: ” + e.age + “<br>”; } } </script> </body> </html> Output Enter your age: 5 Check Age Error: You are too young. Age: 5 If you want to create multiple new classes for the custom errors only to provide the clarified error type and message and don”t want to change the properties of the Error class, you can use the syntax below. class InputError extends Error {}; Let”s learn it via the example below. Example In the code below, we have created 3 different custom classes and extended them with the Error class to create custom errors. In the try{} block, we throw the StringError. In the catch{} block, we used the instanceOf operator to check the type of the error object and print the error message accordingly. <html> <body> <div id = “demo”> </div> <script> const output = document.getElementById(“demo”); class StringError extends Error { }; class NumberError extends Error { }; class BooleanError extends Error { }; try { throw new StringError(“This is a string error”); } catch (e) { if (e instanceof StringError) { output.innerHTML = “String Error”; } else if (e instanceof NumberError) { output.innerHTML = “Number Error”; } else if (e instanceof BooleanError) { output.innerHTML = “Boolean Error”; } else { output.innerHTML = “Unknown Error”; } } </script> </body> </html> Output String Error Multilevel Inheritance You can create a general custom error by extending it with the Error class. After that, you can extend the custom error class to create a more generalized error class. Let”s understand it via the example below. Example In the code below, we have defined the ”NotFound” class and extended it using the Error class. After that, we defined the ”propertyNotFound” and ”valueNotFound” classes and extended them with the ”NotFound” class. Here, we have done the multilevel inheritance. In the try block, we throw a valueNotFound error if the array doesn”t contain 6. In the catch block, we print the error. <html> <body> <div id = “output”> </div> <script> const output = document.getElementById(“output”); class NotFound extends Error { constructor(message) { super(message); this.name = “NotFound”; } } // Further Inheritance class propertyNotFound extends NotFound { constructor(message) { super(message); this.name = “propertyNotFound”; } } // Further Inheritance class ElementNotFound extends NotFound { constructor(message) { super(message); this.name = “ElementNotFound”; } } try { let arr = [1, 2, 3, 4, 5]; // Throw an error if array doesn”t contain 6 if (!arr.includes(6)) { throw new propertyNotFound(“Array doesn”t contain 6″); } } catch (e) { output.innerHTML = e.name + “: ” + e.message; } </script> </body> </html> Output propertyNotFound: Array doesn”t contain 6 You can also throw the propertyNotFound error if any object doesn”t contain the particular property. Print Page Previous Next Advertisements ”;

JavaScript – new Keyword

JavaScript – new Keyword ”; Previous Next 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 – new Constructor(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. new FuncName(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> function Watch(brand, price, type) { this.brand = brand; this.price = price; this.type = type; } const titan = new Watch(”titen”, 4000, ”analog”); const sonata = new Watch(”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”); function Laptop(brand, model, processor) { this.brand = brand; this.model = model; this.processor = processor; this.getLaptop = function () { output.innerHTML += this.brand + “, ” + this.model + “, ” + this.processor + “<br>”; } } const HP = new Laptop(”HP”, “VIKING”, “i7″); const Dell = new Laptop(”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”) class WindowClass { constructor(color, size, type) { this.color = color; this.size = size; this.type = type; } getDetails = function () { output.innerHTML = “Color: ” + this.color + “<br>” + “Size: ” + this.size + “<br>” + “Type: ” + this.type; } } // Creating the instance of WindowClass class const window1 = new WindowClass(”blue”, ”small”, ”wooden”); // Calling function object window1.getDetails(); </script> </body> </html> 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 = new Number(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 = new Number(10); const str = new String(“Hello”); document.getElementById(“output”).innerHTML = “num = ” + num + “, typeof num ” + typeof num + “<br>” + “str = ” + str + “, typeof str ” + typeof str; </script> </body> </html> Output num = 10, typeof num object str = Hello, typeof str object Print Page Previous Next Advertisements ”;

JavaScript – Event Capturing

JavaScript – Event Capturing ”; Previous Next Event Capturing Event capturing in JavaScript is the initial phase in the event propagation model where the event travels from the root of the document tree down to the target element. During this phase, the browser captures the event on the ancestors of the target element before reaching the target itself. Event capturing and event bubbling are two phases in the JavaScript event propagation model. In event capturing, the browser captures and triggers events starting from the root of the document hierarchy and moving down to the target element. On the other hand, event bubbling occurs after the event reaches the target element and then bubbles up from the target to the root. Capturing is useful for handling events at higher-level ancestors, while bubbling is the default behaviour where events propagate from the target back up the hierarchy. Understanding both phases is crucial for effective event handling and manipulation of the event flow. Let us see some important aspects of event capturing. Aspect Description Phase Event capturing is the initial phase in the event propagation model. Direction Capturing occurs in the reverse order of the element hierarchy, from the root of the document tree down to the target element. Use Case Useful when you want to intercept and handle events at a higher-level ancestor before they reach the target element or trigger any bubbling phase handlers. Registration Register event listeners for the capturing phase using the third parameter of addEventListener (e.g., element.addEventListener(”click”, myFunction, true);). Propagation Automatic propagation that precedes the target and bubbling phases. The event flows down the hierarchy, triggering capturing phase handlers on each ancestor. Preventing Default Use event.preventDefault() during the capturing phase to prevent the default behavior of the event before it reaches the target. Stopping Propagation Use event.stopPropagation() in the capturing phase to stop further propagation of the event, preventing it from reaching the target or triggering bubbling phase handlers. Example: Basic Event Capturing In this example, we have a container div (container) and a button (myButton) inside it. Two capturing phase event listeners are added using addEventListener with the true parameter to enable capturing. When you click the button, both capturing phase log messages (Container clicked and Button clicked) will be displayed. This illustrates the capturing phase as the event travels from the document root down to the target element. <!DOCTYPE html> <html> <body> <div id=”container”> <button id=”myButton”>Click me!</button> </div> <div id = “output”></div> <script> const output = document.getElementById(”output”); document.getElementById(”container”).addEventListener(”click”, function(event) { output.innerHTML += ”Capturing phase – Container clicked” + “<br>”; }, true); document.getElementById(”myButton”).addEventListener(”click”, function(event) { output.innerHTML += ”Capturing phase – Button clicked” + “<br>”; }, true); </script> </body> </html> Example: Preventing Default Behaviour In this example, we have a hyperlink (<a>) with an id of “link”. The capturing phase event listener is attached to the link during the capturing phase. When you click the link, the capturing phase log message (Link clicked) will be displayed, and the default behaviour (navigating to a new page) is prevented using event.preventDefault(). If the. preventDefault() was not used, it would have navigated the page to https://www.tutorialspoint.com. <!DOCTYPE html> <html> <body> <a href=”https://www.tutorialspoint.com” id=”link”>Click me to prevent default</a> <script> document.getElementById(”link”).addEventListener(”click”, function(event) { alert(”Capturing phase – Link clicked”); event.preventDefault(); // Prevent the default behavior (e.g., navigating to a new page) }, true); </script> </body> </html> Example: Capturing and Stopping Propagation In this example, the parent div”s capturing phase event listener actively halts propagation through the use of ”event.stopPropagation()”. Only upon clicking the button will you see a log message during capture phase (“Parent clicked”) being displayed; however, it does not trigger any further action within child elements” capturing phases. This indeed showcases an effective method to arrest additional propagation in this particular instance. <!DOCTYPE html> <html> <body> <div id=”parent”> <button id=”child”>Click me!</button> </div> <div id = “output”></div> <script> const output = document.getElementById(”output”); document.getElementById(”parent”).addEventListener(”click”, function(event) { output.innerHTML += ”Capturing phase – Parent clicked” + “<br>”; // Stop further propagation to the child element event.stopPropagation(); }, true); document.getElementById(”child”).addEventListener(”click”, function(event) { output.innerHTML += ”Capturing phase – Child clicked” + “<br>”; }, true); </script> </body> </html> Print Page Previous Next Advertisements ”;