Friday, 24 November 2017


 JavaScript - Document Object Model


The usual html pages are static.The user does not have an opportunity to interact with them . The usual is too boring.To make the page more interactive and responsive we use java script DOM.
When a web page is loaded, the browser creates a Document Object Model of the page.A Document object represents the HTML document that is displayed in that window.The Document Object Model  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.This makes the page more interactive.

The DOM model can be visualized as a tree.The Objects are organized in a hierarchy. 


The HTML Tree of Objects


Image result for js dom



DOM Elements And Objects

The  reason why HTML elements are so versatile when viewed via the DOM is because they share a lot of similarities with java script  objects. DOM elements contain properties that allow us o get values and call methods.Each object of the DOM can be visualized as a node of the tree.


Creating DOM Elements
You can create elements using createElement method.You can call it via document object method and pass in the tag name of the element you wish to create. Eg: var new=document.createElement("p");
The new element which is created is not a part of DOM. It is floating aimlessly as it is not attached to anything. There are two things we need to do.
  1. Find an element that will act as the parent.
  2. Use append child and attach the new element to that parent.
The parent is a body element that can be accessed via document.body
appendChild will always add the new element to the end of whatever chidren a parent may have.But if you don't want the new element to be added at the end instead you want to insert the new element before the last child you can use insertBefore function on the parent.

   
Traversing the DOM
Window and document are global properties.Each object has many properties.
Properties that will help us to traverse the DOM tree are:
  • firstChild
  • lastChild
  • parentNode
  • children
  • previousSibling
  • nextSibling


Node Parent , Children and Sibling

Related image

No comments:

Post a Comment