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
- getElementById: To access elements and attributes whose id is set.
- innerHTML: To access the content of an element.
Try this yourself:
- 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:
- createElement: To create new element
- removeChild: Remove an element
- 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', functionname) |
Try this yourself: