Dom Manipulations

Javascript DOM Manipulations

The DOM (Document Object Model) represents a document as a hierarchical tree structure and each element in the document tree is called a Node in the DOM. The main object is the Document Object, which in turn contains several other child objects. Each and every single element in the document will have a corresponding presence in the DOM tree. The DOM has several methods and properties that you can access any element on the page, add new ones, modify or remove elements from the document.

Creating Nodes

In order to create new elements in the DOM, it provides a generic method createElement() , that takes as an argument an HTML tag name, and returns a plain DOM node of the specified type.

Syntax

example

  • Red
  • Blue
  • Green

Full Source

Above program first create an LI node, then it crate a textnode for displaying text and then it append the text node to new LI element and finally the new node is append to the existing "list".

appendChild(element):

The appendChild() method appends the DOM element as a child of parentNode, at the end of its existing child nodes.

insertBefore(element, targetNode):

The insertBefore() method inserts the DOM element as a child of parentNode and a sibling of targetNode just before it in the current document.

replaceChild(element, targetNode):

The replaceChild method replaces targetNode with element.

Modifying Node

You can modify existing elements in the DOM by changing their properties, content, style or even moving them completely from one place in the DOM to another.

Modify content

Javascript DOM Modify content

The Node.innerHTML provides an interface to the HTML inside of a node. This method will sets or returns the inner HTML of an element. It does not return any HTML markup. When set the content with this method, it will erases all content within the node and inserts the supplied text.

InnerHTML Text

Full Source

Modifying Styles

You can change the style of an element in the DOM similar to change the content in the above example.

InnerHTML Text

Full Source

Removing Nodes

Javascript DOM Removing Nodes

Similar to modifying DOM , it also allows us to delete the target nodes. The removeChild() method delete the targetnode from the parent node.

Syntax

  • Red
  • Blue
  • Green

Full Source