How to use DOM and Events in JavaScript

JavaScript can access all the elements in a webpage making use of Document Object Model (DOM). In fact, the web browser creates a DOM of the webpage when the page is loaded. The DOM model is created as a tree of objects like this:
What can be achieved using DOM?
Using DOM, JavaScript can perform multiple tasks. It can create new elements and attributes, change the existing elements and attributes and even remove existing elements and attributes. JavaScript can also react to existing events and create new events in the page.
Common Methods and Properties
  1.  getElementById:  To access elements and attributes whose id is set.
  2.  innerHTML: To access the content of an element.
Try this yourself:
This code is editable. Click Run to Execute
1
2
    <html>
3
4
    <head>
5
6
    <title>DOM!!!</title>
7
8
    </head>
9
10
    <body>
11
12
    <h1 id="one">Welcome</h1>
13
14
    <p>This is the welcome message.</p>
15
16
    <h2>Technology</h2>
17
18
    <p>This is the technology section.</p>
19
20
    <script type="text/javascript">
21
22
    var text = document.getElementById("one").innerHTML;
23
24
    alert("The first heading is " + text);
25
26
    </script>
27
28
    </body>
29
30
    </html>
31
  1. getElementsByTagName: To access elements and attributes using tag name. This method will return an array of all the items with the same tag name.
Try this yourself:
This code is editable. Click Run to Execute
1
2
         <html>
3
4
    <head>
5
6
    <title>DOM!!!</title>
7
8
    </head>
9
10
    <body>
11
12
    <h1>Welcome</h1>
13
14
    <p>This is the welcome message.</p>
15
16
    <h2>Technology</h2>
17
18
    <p id="second">This is the technology section.</p>
19
20
    <script type="text/javascript">
21
22
    var paragraphs = document.getElementsByTagName("p");
23
24
    alert("Content in the second paragraph is " + paragraphs[1].innerHTML);
25
26
    document.getElementById("second").innerHTML = "The orginal message is changed.";
27
28
    </script>
29
30
    </body>
31
32
    </html>
33
  1.      createElement:  To create new element
  2.      removeChild: Remove an element
  3.      You can add an event handler to a particular element like this:
?
1
2
3
4
5
6
7
document.getElementById(<em>id</em>).onclick=function()</p>
 
{
 
lines of code to be executed</p>
 
}
OR
?
1
document.getElementById(id).addEventListener(&#39;click&#39;, functionname)
Try this yourself:
This code is editable. Click Run to Execute
1
2
    <html>
3
4
    <head>
5
6
    <title>DOM!!!</title>
7
8
    </head>
9
10
    <body>
11
12
    <input type="button" id="btnClick" value="Click Me!!" />
13
14
    <script type="text/javascript">
15
16
    document.getElementById("btnClick").addEventListener("click", clicked);
17
18
    function clicked()
19
20
    {
21
22
    alert("You clicked me!!!");
23
24
    }
25
26
    </script>
27
28
    </body>
29
30
    </html>
31