Document Object Model & Javascript
-
The Document Object Model is the model that describes how all elements in an HTML page, like input fields,table, images, paragraphs,links etc. are related to the topmost structure i.e. the document itself.
-
Document Object Model represent the current web page as a tree of javascript objects.
-
DOM allows us to view and modify the page elements using javascript after page has loaded.
Nodes:
In Document Object Model everything on your web page whatever it may be exactly is a Node.
There are three types of nodes possible
-
Element Node –These are the HTML tags and can have attriburtes and children.
-
Text Node –These are text in side block elements and can’t have child & attribute.
-
Attribute Node –These are attribute value pair inside tag and can’t have child,attribute.
Suppose if you have written <p>Hello Abhishek</p> that means you have created two nodes i.e.
an element node ‘p’ and a text node whose content are ‘Hello Abhishek’.As text node is inside the
paragraph tag hence it is child node of the element node ‘p’.There are methods using which you
can create nodes
>>createDocumentFragment() Returns a document fragment that can be used to add
multiple nodes to the document
>>createElement(’element_name’) Returns a new element of type element_name
>>createTextNode(’text content’) Returns a text node with a string value matching the
text content
Referencing the Nodes:
There are methods using which one can obtain the reference of a node.
>>getElementById(’element id’) Returns a reference to the element with the specified
id
>>getElementByTagName(’element name’) Returns a collection of all elements with the
specified element name
Traversing the DOM tree:
Document Object Model parses the entire document in a tree structure. There
are properties associated with each node using which one can obtain access to any node in the
Dom tree.
>>childNodes[] A collection of all text nodes and element nodes the
node contains directly if node is an element node or
document node
>>parentNode A reference to the containing node
>>firstChild The first entry in the childNodes collection
>>lastChild The last entry in the childNodes collection
>>nextSibling The next entry in the childNodes collection of the
parent node
>>previousSibling The previous entry in the childNodes collection of the
parent node
Modifying the DOM Tree:
Every DOM node has various methods
>>appendChild(node) Add the specified node at the end of the child node
list of the parent node.
>>insertBefore(newchild,oldchild) Places the new node before the old child in the child
node list
>>removeChild(node) Removes the node from the nodes child list
>>replaceChild(newchild, oldchild) Replaces the old child from the new child in child
node list
