JavaScript HTML DOM

Dom stands for Document Object Model. When a web page is loaded the browser creates a DOM of the page.

Usually the DOM will treat the whole page as a document and all the HTML tags as elements. JavaScript can read, add, delete and edit all HTML elements, attributes of HTML elements and their events. It can also change all CSS styles.

HTML and JavaScript are two different languages that can’t communicate with each other. This problem is solved by browser treating each HTML tag as a JavaScript Object so JavaScript can then speak to HTML.

  • The browsers creates a JS object out of each HTML tag
  • Each tag object has inbuilt properties and methods
  • DOM elements are also called nodes
  • We represent DOM elements as a family tree
  • Each node has ancestors, descendants, a parent, children, siblings etc..

Examples of editing HTML DOM using JavaScript

Below are few examples of hows JavaScript can edit HTML DOM

Subscribing handlers to events:

element.addEventListener(type:string, handler:function)

 

Manipulating content:

element.innerHTML = some new value here

 

Executing code after given delay:

setTimeout(code:function, delay:ms)

 

Manipulating attributes:

element.attributeName = some new value
element.setAttribute(attrName, attrValue) -> write mode
element.getAttribute(attrName) -> read mode
element.removeAttribute(attrName) -> delete mode

 

Manipulating css:

element.style.cssPropertyName = a new css value