Document Object Model in JavaScript
This section covers the JavaScript Document Object Model (DOM) and shows you how to manipulate DOM elements effectively.
The document object refers to your whole HTML page. After
you load an object into the web browser, it immediately
becomes a document object, which is the root element
representing the html document. It comes with both
properties and methods. The document object helps us add
content to the web pages.
It is an object of the window, which means that having:
window.document or simply
document
document as a hierarchy of nodes
The DOM represents an HTML document as a hierarchy of nodes. Consider the following HTML document:
<html> <head> <title>JavaScript DOM</title> </head> <body> <p>Hello DOM!</p> </body> </html>
The following tree represents the above HTML document:
DOM Methods
DOM methods are the actions that you can perform on the html elements. The DOM properties are the values of the HTML elements which one can set or change. The following are the document object methods:
Finding HTML Elements
document.getElementById(id) - Find an element by element id
getElementsByName() – select elements by name.
document.getElementsByTagName(name) - Find elements by tag name
document.getElementsByClassName(name) - Find elements by class name
querySelector() – select elements by CSS selectors.
Changing HTML Elements
element.innerHTML = new html content - Change the inner HTML of an element
element.attribute = new value - Change the attribute value of an HTML element
element.style.property = new style - Change the style of an HTML element
element.setAttribute(attribute, value) - Change the attribute value of an HTML element
Adding and Deleting Elements
document.createElement(element) - Create an HTML element
document.removeChild(element) - Remove an HTML element
document.appendChild(element) - Add an HTML element
document.replaceChild(new, old) - Replace an HTML element
document.write(text) - Write into the HTML output stream
Adding Events Handlers
document.getElementById(id).onclick = function(){code} Adding event handler code to an onclick event