JavaScript - SPLessons
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

JavaScript DOM

JavaScript DOM

shape Introduction

JavaScript DOM (Document Object Model) is the virtual map of a web page currently being loaded in the browser. While using JavaScript, following should be done: => First thing is the browser loads the web page, then browser takes the HTML, process and renders it to a web page. This is the document-1. => The second thing is to create JavaScript DOM(Document Object Model). This is the document-2 that consists of objects, which can be used to represent the HTML.

shape Description

Every web page is considered as a Document Object and every tag is referred as a node inside the JavaScript DOM. JavaScript can be used to manipulate all these elements irrespective of whether they are placed between tags or not.

Functions of DOM

Document Object Model can perform all the functions related to JavaScript. JavaScript DOM can
  • Create, change and remove all the HTML elements and attributes.
  • Create and respond to all HTML DOM events.
  • Make changes to CSS styles in a page.

shape Conceptual figure

In document object, there are 4 nodes which will be executed sequentially, they are:

shape Examples

Below example illustrates the JavaScript DOM concept and various elements in it. [html] <!DOCTYPE html> <html> <head> <title>Document Object MOdel</title> <script type="text/javascript" src="jscode.js"></script> </head> <body> <h1 id="title"> SPLessons tutorial </h1> <div id="main"> <p id="first">This is first paragraph</p> <p id="second"> <strong>This is SEcond paragraph<strong> </p> </div> <div id="form"> <input type="submit" id="clickme" value="Click Me"/> <a href="http://www.splessons.com">Welcome</a> </div> </body> </html> [/html] The DOM hierarchy for the above example is as follows.

DOM Methods

shape Description

DOM is an Application Programming Interface that has the properties and methods of every object. Variables inside an object are called as Properties and Methods are the actions that an object does. getElementById,getElementsByTagName and getElementByClassName are the three important methods and innerHTML is a property.

getElementById

getElementById method is used to grab the elementID. object.html [html] <!DOCTYPE html> <html> <head> <title>Document Object MOdel</title> <script type="text/javascript" src="jscode.js"></script> </head> <body> <p id="para1">This is an example of DOM Method</p> <button onclick="changeStyle()">Submit</button> </body> </html> [/html] jscode.js [c] function changeStyle() { var text = document.getElementById("para1").style.backgroundColor= "cyan"; } [/c] Output: When the Submit button is clicked, the following output appears. In the above example, elementID is given as "para1". When the JavaScript encounters this ID, it is parsed by the "getElementById" to assign the property "backgroundColor" to the id text using the "style" object.

getElementByTagName

getElementByTagName method is used to grab the elements tag. This method builds a node list to differentiate the elements by giving the index. Below is an example. object.html [html] <!DOCTYPE html> <html> <head> <title>Document Object MOdel</title> <script type="text/javascript" src="jscode.js"></script> </head> <body> <p id="para1">This is an example of DOM Method</p> <p id="para2">This is an example of DOM Method</p> <button onclick="changeStyle()">Submit</button> </body> </html> [/html] jscode.js [c] function changeStyle() { var paragraph = document.getElementsByTagName("p"); var changeParaText = paragraph[0].style.fontStyle = "italic"; var changeParaText = paragraph[1].style.fontStyle = "normal"; } [/c] Output: The below output appears when the submit button is clicked. In the above example, a node list with two nodes are created for paragraph and the elements are grabbed by the tag name<p>

getElementByClassName

getElementsByClassName is used to select the elements by class name. This method also creates the node list similar to getElementsByTagName() method. object.html [html] <!DOCTYPE html> <html> <head> <title>Document Object MOdel</title> <script type="text/javascript" src="jscode.js"></script> </head> <body> <p class="para">This is an example of DOM Method</p> <p class="para">This is an example of DOM Method</p> <button onclick="changeStyle()">Submit</button> </body> </html> [/html] jscode.js [c] function changeStyle() { var paragraph = document.getElementsByTagName("p"); var changeText = paragraph[0].style.color = "red"; var changeText = paragraph[1].style.color = "cyan"; }[/c] Output: After clicking submit button, the following output appears:

DOM Documents

shape Description

A web page is represented using Document Object. Before going to access any element in the HTML page, a document object is considered first. Some of the document objects are given below.

Detecting Elements in HTML

Method Description
document.getElementByID(id) Used to detect an element by its id.
document.getElementsByTagName(name) Used to detect an element by its tag name.
document.getElementsByClassName(name) Used to detect and element by its class name.

Changing Elements in HTML

Method Description
element.attribute = new value Used to change the value of attribute of an HTML element.
element.setAttribute(attribute,value) Used to change the value of attribute of an HTML element.
element.innerHTML = new html content Used to change the inner HTML of an element.
element.style.property = new style Used to change the style of an HTML element.

Add and Delete Elements in HTML

Method Description
document.createElement(element) Used to create a HTML element.
document.appendChild(element) Used to add a HTML element.
document.replaceChild(element) Used to replace a HTML element.
document.removeChild(element) Used to remove a HTML element.
document.write(text) Used to write in output stream of HTML.

DOM Elements

shape Description

DOM Elements are used to find the elements in a HTML page and access them. Finding HTML elements can be done by using
  • getElementById
  • getElementsByTagName
  • getElementsByClassName
  • CSS Selectors
  • Object Collections
The first three are given in detail in DOM Methods.

CSS Selectors

HTML elements can be selected using CSS selectors like id, types, and class names. For this, a method called querySelectorAll() is used. Below is an example for querySelectorAll() method. [html] <!DOCTYPE html> <html> <body> <p>Hello World!</p> <p class="intro">Go Green!!! Save Planet.</p> <p class="intro">This example demonstrates the <b>querySelectorAll</b> method.</p> <p id="text"></p> <script> var x = document.querySelectorAll("p.intro"); document.getElementById("text").innerHTML = 'The first paragraph (index 0) with class "intro" is <br>' + x[0].innerHTML; </script> </body> </html> [/html] Output

Object Collections

Object Collections are used to find form elements. [html] <!DOCTYPE html> <html> <body> <form id="val" action="form_action.asp"> First name: <input type="text" name="fname" value="Mickey"><br> Last name: <input type="text" name="lname" value="Mouse"><br><br> <input type="submit" value="Submit"> </form> <p>Click "Try it" to display the value of each element in the form.</p> <button onclick="myFunction()">Try it</button> <p id="text"></p> <script> function myFunction() { var x = document.forms["val"]; var text = ""; var i; for (i = 0; i < x.length ;i++) { text += x.elements[i].value + "<br>"; } document.getElementById("text").innerHTML = text; } </script> </body> </html> [/html] Output

DOM HTML

shape Description

DOM HTML is important while changing the content of the HTML elements using JavaScript. Changing HTML elements can be done easily using innerHTML property.

innerHTML

The innerHTML property allows the HTML document to write dynamic HTML. object.html [html] <!DOCTYPE html> <html> <head> <title>Document Object MOdel</title> <script type="text/javascript" src="jscode.js"></script> </head> <body> <p>This is an example of DOM Method</p> <p>This is an example of DOM Method</p> <button onclick="changeStyle()">Submit</button> </body> </html> [/html] jscode.js [c] function changeStyle() { var paragraph = document.getElementsByTagName("p"); var changeParaText = paragraph[0].innerHTML = "New Text 1"; var changeParaText = paragraph[1].innerHTML = "New Text 2"; }[/c] Output: When the Submit is clicked, the text in the HTML document changes to the new text as shown below. Attributes can also be changed using HTML DOM. For this, replace innerHTML with the attribute name in the above example.

DOM Event

shape Description

In programs, there exists a scenario where a statement will be executed only when there is response from the users on the forms. For that purpose, events are used. An event is an action that happens on the web page. Every website is made responsive through events. Events trigger JavaScript code to respond to the actions detected by JavaScript. Events are defined in HTML tags. Some examples of the events are as follows:
  • Mouse click
  • Web page loading or image loading
  • Selecting an input field in the HTML form
  • Submit an HTML form
  • Keystroke
  • Mouse over hotspot on a web page.

shape Syntax

<HTML_element event_name="JavaScript code">

shape More Info

When creating an event, you need to: When the event happens(till then JavaScript code waits), the JavaScript function will be called. For example,
<button onclick=”changeColor()”>Submit</button>
In the above example, onclick event is placed in the button element. Note:

shape Examples

Onclick Event

This is the most commonly used event in JavaScript. When the user left-clicks on mouse, this event will be generated. [html] <!Doctype html> <html> <head> <meta charset="utf-8"/> <title> JavaScript - Events </title> <script type="text/javascript"> </script> </head> <body> <form> <input type="button" value="Click me" onclick="alert('You clicked me');"/> </form> </body> </html>[/html] Output

onmouseover() event

When the mouse is moved over HTML element, this event will be generated and works with every HTML element.

onmouseout() event

When the mouse is moved away from specified HTML element, this event will be triggered.
[html] <!DOCTYPE html> <html> <body> <h1 onmouseover="style.color='red'" onmouseout="style.color='black'">Mouse over this text</h1> </body> </html> [/html] Output By placing the mouse on text, you will get the following output: After placing the mouse on text, the output is as follows.

DOM Event Listener

shape Description

JavaScript keeps the HTML and event handling separate. It can work on any JavaScript DOM element and HTML element. It allows you to add more than one handler for an event.

addEventListener

addEventListener() is the optimum way of adding event listeners to HTML elements in DOM. It is the method that works on objects and can bind the events to objects. Syntax: element.addEventListener(event,handler,phase) [html] <!DOCTYPE html> <html> <head> <p>This example uses the addEventListener() method to attach a click event to a button.</p> <script> document.write("Before adding click event to the button<br><br>"); </script> </head> <body> <button id="myBtn">Try it</button> <p id="text"></p> <script> document.getElementById("myBtn").addEventListener("click", displaytext); function displaytext() { document.getElementById("text").innerHTML = "After adding click event to the button"; } </script> </body> </html> [/html] Output: After clicking the Try it button, the following output appears.

Multiple Event handlers to single element.

Event Listeners allow adding multiple events to a single element. For example, [html] <!DOCTYPE html> <html> <body> <p>This example uses the addEventListener() method to add many events on the same button.</p> <button id="myBtn">Try it</button> <p id="demo"></p> <script> var x = document.getElementById("myBtn"); x.addEventListener("mouseover", myFunction); x.addEventListener("click", mySecondFunction); x.addEventListener("mouseout", myThirdFunction); function myFunction() { document.getElementById("demo").innerHTML += "Moused over!<br>"; } function mySecondFunction() { document.getElementById("demo").innerHTML += "Clicked!<br>"; } function myThirdFunction() { document.getElementById("demo").innerHTML += "Moused out!<br>"; } </script> </body> </html>[/html]

removeEventListener

By using this event handler method, an event can be removed. [html] <!DOCTYPE html> <html> <head> <style> #myDIV { background-color: coral; border: 1px solid; padding: 50px; color: white; } </style> </head> <body> <div id="myDIV">This div element has an onmousemove event handler that displays a random number every time you move your mouse inside this orange field. <p>Click the button to remove the DIV's event handler.</p> <button onclick="removeHandler()" id="myBtn">Try it</button> </div> <p id="demo"></p> <script> document.getElementById("myDIV").addEventListener("mousemove", myFunction); function myFunction() { document.getElementById("demo").innerHTML = Math.random(); } function removeHandler() { document.getElementById("myDIV").removeEventListener("mousemove", myFunction); } </script> </body> </html> [/html] Output: When the button Try it is clicked, the value will be fixed.

Animations

shape Description

Animation is the advanced feature of JavaScript. To perform animations, a container should be created first. For example,
Animation is performed here.
For the created elements, styles have to be applied.
#container { width: 600; height: 400px; position: relative; background: black; } #animate { width: 50px; height: 50px; position: absolute; background: cyan; }

shape Examples

While performing animations, program changes are gradually called by the timer. Example for Animations are as follows. [html] <!DOCTYPE html> <html> <style> #container { width: 200px; height: 200px; position: relative; background: black; } #animate { width: 20px; height: 20px; position: absolute; background: cyan; } </style> <body> <p> <button onclick="myMove()">Click Me</button> </p> <div id ="container"> <div id ="animate"></div> </div> <script> function myMove() { var elem = document.getElementById("animate"); var pos = 0; var id = setInterval(frame, 5); function frame() { if (pos == 175) { clearInterval(id); } else { pos++; elem.style.top = pos + 'px'; elem.style.left = pos + 'px'; } } } </script> </body> </html> [/html] OutputWhen the Click Me button is clicked, the box moves to a position as shown below.

Summary

shape Key Points

  • JavaScript DOM (Document Object Model) refers to a web page in the browser.
  • Document, attribute, element and text are the four nodes in JavaScript DOM.
  • getElementById, getElementsByTagName and getElementsByClassName are the 3 methods and innerHTML is the property of DOM.
  • JavaScript DOM Events handle user responses.
  • To perform animations, a container is required.