0% found this document useful (0 votes)
52 views17 pages

Document Object Model

The document represents the HTML document loaded in the browser. It is the root element that represents the entire document and has properties and methods to dynamically access and modify the content, structure, and style of the document. Key properties of the document object include document.getElementById(), document.getElementsByName(), and document.getElementsByTagName() which return elements based on id, name, and tag respectively. The document object's innerHTML and innerText properties can be used to dynamically write and modify content in the document. Form validation can also be done using JavaScript to validate user input before submission.

Uploaded by

Manikandan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views17 pages

Document Object Model

The document represents the HTML document loaded in the browser. It is the root element that represents the entire document and has properties and methods to dynamically access and modify the content, structure, and style of the document. Key properties of the document object include document.getElementById(), document.getElementsByName(), and document.getElementsByTagName() which return elements based on id, name, and tag respectively. The document object's innerHTML and innerText properties can be used to dynamically write and modify content in the document. Form validation can also be done using JavaScript to validate user input before submission.

Uploaded by

Manikandan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Document Object Model

The document object represents the whole html document.

When html document is loaded in the browser, it becomes a document


object. It is the root element that represents the html document. It has
properties and methods. By the help of document object, we can add
dynamic content to our web page.

As mentioned earlier, it is the object of window. So


1. window.document

Is same as
1. document

According to W3C - "The W3C Document Object Model (DOM) is a


platform and language-neutral interface that allows programs and
scripts to dynamically access and update the content, structure, and
style of a document."

Properties of document object


Let's see the properties of document object that can be accessed and modified by the
document object.
Methods of document object
We can access and change the contents of document by its methods.

The important methods of document object are as follows:

Method Description

write("string") writes the given string on the doucment.

writeln("string") writes the given string on the doucment with newline character at the end.

getElementById() returns the element having the given id value.

getElementsByName() returns all the elements having the given name value.
getElementsByTagName() returns all the elements having the given tag name.

getElementsByClassName() returns all the elements having the given class name.

Accessing field value by document object


In this example, we are going to get the value of input text by user. Here, we are
using document.form1.name.value to get the value of name field.

Here, document is the root element that represents the html document.

form1 is the name of the form.

name is the attribute name of the input text.

value is the property, that returns the value of the input text.

Let's see the simple example of document object that prints name with welcome message.

1. <script type="text/javascript">
2. function printvalue(){
3. var name=document.form1.name.value;
4. alert("Welcome: "+name);
5. }
6. </script>
7.
8. <form name="form1">
9. Enter Name:<input type="text" name="name"/>
10. <input type="button" onclick="printvalue()" value="print name"/>
11. </form>

Javascript - document.getElementById()
method
The document.getElementById() method returns the element of specified id.

In the previous page, we have used document.form1.name.value to get the value of the
input value. Instead of this, we can use document.getElementById() method to get value of
the input text. But we need to define id for the input field.
Let's see the simple example of document.getElementById() method that prints cube of the
given number.

1. <script type="text/javascript">
2. function getcube(){
3. var number=document.getElementById("number").value;
4. alert(number*number*number);
5. }
6. </script>
7. <form>
8. Enter No:<input type="text" id="number" name="number"/><br/>
9. <input type="button" value="cube" onclick="getcube()"/>
10. </form>

Javascript - document.getElementsByName()
method
The document.getElementsByName() method returns all the element of specified name.

The syntax of the getElementsByName() method is given below:

1. document.getElementsByName("name")

Here, name is required.

Example of document.getElementsByName() method


In this example, we going to count total number of genders. Here, we are using
getElementsByName() method to get all the genders.

1. <script type="text/javascript">
2. function totalelements()
3. {
4. var allgenders=document.getElementsByName("gender");
5. alert("Total Genders:"+allgenders.length);
6. }
7. </script>
8. <form>
9. Male:<input type="radio" name="gender" value="male">
10. Female:<input type="radio" name="gender" value="female">
11.
12. <input type="button" onclick="totalelements()" value="Total Genders">
13. </form>

Javascript -
document.getElementsByTagName() method
The document.getElementsByTagName() method returns all the element of specified
tag name.

The syntax of the getElementsByTagName() method is given below:

1. document.getElementsByTagName("name")

Here, name is required.

Example of document.getElementsByTagName()
method
In this example, we going to count total number of paragraphs used in the document. To do
this, we have called the document.getElementsByTagName("p") method that returns the
total paragraphs.

1. <script type="text/javascript">
2. function countpara(){
3. var totalpara=document.getElementsByTagName("p");
4. alert("total p tags are: "+totalpara.length);
5.
6. }
7. </script>
8. <p>This is a pragraph</p>
9.

<p>Here we are going to count total number of paragraphs by getElementByTagName() m


ethod.</p>
10. <p>Let's see the simple example</p>
11. <button onclick="countpara()">count paragraph</button>

Another example of
document.getElementsByTagName() method
In this example, we going to count total number of h2 and h3 tags used in the document.

1. <script type="text/javascript">
2. function counth2(){
3. var totalh2=document.getElementsByTagName("h2");
4. alert("total h2 tags are: "+totalh2.length);
5. }
6. function counth3(){
7. var totalh3=document.getElementsByTagName("h3");
8. alert("total h3 tags are: "+totalh3.length);
9. }
10. </script>
11. <h2>This is h2 tag</h2>
12. <h2>This is h2 tag</h2>
13. <h3>This is h3 tag</h3>
14. <h3>This is h3 tag</h3>
15. <h3>This is h3 tag</h3>
16. <button onclick="counth2()">count h2</button>
17. <button onclick="counth3()">count h3</button>

Javascript - innerHTML
The innerHTML property can be used to write the dynamic html on the html document.

It is used mostly in the web pages to generate the dynamic html such as registration form,
comment form, links etc.

Example of innerHTML property


In this example, we are going to create the html form when user clicks on the button.

In this example, we are dynamically writing the html form inside the div name having the id
mylocation. We are identifing this position by calling the document.getElementById()
method.

1. <script type="text/javascript" >


2. function showcommentform() {
3.

var data="Name:<input type='text' name='name'><br>Comment:<br><textarea rows


='5' cols='80'></textarea>
4. <br><input type='submit' value='Post Comment'>";
5. document.getElementById('mylocation').innerHTML=data;
6. }
7. </script>
8. <form name="myForm">
9. <input type="button" value="comment" onclick="showcommentform()">
10. <div id="mylocation"></div>
11. </form>

Show/Hide Comment Form Example using


innerHTML
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title>First JS</title>
5. <script>
6. var flag=true;
7. function commentform(){
8.

var cform="<form action='Comment'>Enter Name:<br><input type='text' name='name'


/><br/>
9. Enter Email:<br><input type='email' name='email'/><br>Enter Comment:<br/>
10.

<textarea rows='5' cols='70'></textarea><br><input type='submit' value='Post Com


ment'/></form>";
11. if(flag){
12. document.getElementById("mylocation").innerHTML=cform;
13. flag=false;
14. }else{
15. document.getElementById("mylocation").innerHTML="";
16. flag=true;
17. }
18. }
19. </script>
20. </head>
21. <body>
22. <button onclick="commentform()">Comment</button>
23. <div id="mylocation"></div>
24. </body>
25. </html>

Javascript - innerText
The innerText property can be used to write the dynamic text on the html document. Here,
text will not be interpreted as html text but a normal text.

It is used mostly in the web pages to generate the dynamic content such as writing the
validation message, password strength etc.

Javascript innerText Example


In this example, we are going to display the password strength when releases the key after
press.

1. <script type="text/javascript" >


2. function validate() {
3. var msg;
4. if(document.myForm.userPass.value.length>5){
5. msg="good";
6. }
7. else{
8. msg="poor";
9. }
10. document.getElementById('mylocation').innerText=msg;
11. }
12.
13. </script>
14. <form name="myForm">
15. <input type="password" value="" name="userPass" onkeyup="validate()">
16. Strength:<span id="mylocation">no strength</span>
17. </form>

JavaScript Form Validation


t is important to validate the form submitted by the user because it can have inappropriate
values. So, validation is must to authenticate user.
JavaScript provides facility to validate the form on the client-side so data processing will be
faster than server-side validation. Most of the web developers prefer JavaScript form
validation.

Through JavaScript, we can validate name, password, email, date, mobile numbers and
more fields.

JavaScript Form Validation Example


In this example, we are going to validate the name and password. The name can’t be empty
and password can’t be less than 6 characters long.

Here, we are validating the form on form submit. The user will not be forwarded to the next
page until given values are correct.

1. <script>
2. function validateform(){
3. var name=document.myform.name.value;
4. var password=document.myform.password.value;
5.
6. if (name==null || name==""){
7. alert("Name can't be blank");
8. return false;
9. }else if(password.length<6){
10. alert("Password must be at least 6 characters long.");
11. return false;
12. }
13. }
14. </script>
15. <body>
16.

<form name="myform" method="post" action="abc.jsp" onsubmit="return validateform()"


>
17. Name: <input type="text" name="name"><br/>
18. Password: <input type="password" name="password"><br/>
19. <input type="submit" value="register">
20. </form>
JavaScript Events
The change in the state of an object is known as an Event. In html, there are various events which
represents that some activity is performed by the user or by the browser. When javascript code is included
in HTML, js react over these events and allow the execution. This process of reacting over the events is
called Event Handling. Thus, js handles the HTML events via Event Handlers.

For example, when a user clicks over the browser, add js code, which will execute the task to be
performed on the event.

Some of the HTML events and their event handlers are:

Mouse events:

Event Performed Event Handler Description

click onclick When mouse click on an element

mouseover onmouseover When the cursor of the mouse comes over the element

mouseout onmouseout When the cursor of the mouse leaves an element

mousedown onmousedown When the mouse button is pressed over the element

mouseup onmouseup When the mouse button is released over the element

mousemove onmousemove When the mouse movement takes place.

Keyboard events:

Event Performed Event Handler Description

Keydown & Keyup onkeydown & onkeyup When the user press and then release the key

Form events:

Event Performed Event Handler Description

focus onfocus When the user focuses on an element

submit onsubmit When the user submits the form

blur onblur When the focus is away from a form element


change onchange When the user modifies or changes the value of a form element

Window/Document events

Event Performed Event Handler Description

load onload When the browser finishes the loading of the page

unload onunload When the visitor leaves the current webpage, the browser unloads it

resize onresize When the visitor resizes the window of the browser

Let's discuss some examples over events and their handlers.

Click Event

1. <html>
2. <head> Javascript Events </head>
3. <body>
4. <script language="Javascript" type="text/Javascript">
5. <!--
6. function clickevent()
7. {
8. document.write("This is JavaTpoint");
9. }
10. //-->
11. </script>
12. <form>
13. <input type="button" onclick="clickevent()" value="Who's this?"/>
14. </form>
15. </body>
16. </html>

MouseOver Event

1. <html>
2. <head>
3. <h1> Javascript Events </h1>
4. </head>
5. <body>
6. <script language="Javascript" type="text/Javascript">
7. <!--
8. function mouseoverevent()
9. {
10. alert("This is JavaTpoint");
11. }
12. //-->
13. </script>
14. <p onmouseover="mouseoverevent()"> Keep cursor over me</p>
15. </body>
16. </html>

Focus Event

1. <html>
2. <head> Javascript Events</head>
3. <body>
4. <h2> Enter something here</h2>
5. <input type="text" id="input1" onfocus="focusevent()"/>
6. <script>
7. <!--
8. function focusevent()
9. {
10. document.getElementById("input1").style.background=" aqua";
11. }
12. //-->
13. </script>
14. </body>
15. </html>

Keydown Event

1. <html>
2. <head> Javascript Events</head>
3. <body>
4. <h2> Enter something here</h2>
5. <input type="text" id="input1" onkeydown="keydownevent()"/>
6. <script>
7. <!--
8. function keydownevent()
9. {
10. document.getElementById("input1");
11. alert("Pressed a key");
12. }
13. //-->
14. </script>
15. </body>
16. </html>

Load event

1. <html>
2. <head>Javascript Events</head>
3. </br>
4. <body onload="window.alert('Page successfully loaded');">
5. <script>
6. <!--
7. document.write("The page is loaded successfully");
8. //-->
9. </script>
10. </body>
11. </html>

avaScript addEventListener()
The addEventListener() method is used to attach an event handler to a particular element. It does not
override the existing event handlers. Events are said to be an essential part of the JavaScript. A web
page responds according to the event that occurred. Events can be user-generated or generated by
API's. An event listener is a JavaScript's procedure that waits for the occurrence of an event.

The addEventListener() method is an inbuilt function of JavaScript. We can add multiple event handlers to
a particular element without overwriting the existing event handlers.

Syntax

1. element.addEventListener(event, function, useCapture);

Although it has three parameters, the parameters event and function are widely used. The third
parameter is optional to define. The values of this function are defined as follows.

Parameter Values
event: It is a required parameter. It can be defined as a string that specifies the event's name.

Note: Do not use any prefix such as "on" with the parameter value. For example, Use "click" instead
of using "onclick".

function: It is also a required parameter. It is a JavaScript function which responds to the event occur.

useCapture: It is an optional parameter. It is a Boolean type value that specifies whether the event is
executed in the bubbling or capturing phase. Its possible values are true and false. When it is set to true,
the event handler executes in the capturing phase. When it is set to false, the handler executes in the
bubbling phase. Its default value is false.

1. <!DOCTYPE html>
2. <html>
3. <body>
4. <p> This is an example of adding multiple events to the same element. </p>
5. <p> Click the following button to see the effect. </p>
6. <button id = "btn"> Click me </button>
7. <p id = "para"></p>
8. <p id = "para1"></p>
9. <script>
10. function fun() {
11. alert("Welcome to the javaScript ");
12. }
13.
14. function fun1() {
15. document.getElementById("para").innerHTML = "This is second function";
16.
17. }
18. function fun2() {
19. document.getElementById("para1").innerHTML = "This is third function";
20. }
21. var mybtn = document.getElementById("btn");
22. mybtn.addEventListener("click", fun);
23. mybtn.addEventListener("click", fun1);
24. mybtn.addEventListener("click", fun2);
25. </script>
26. </body>
27. </html>

You might also like