DOM concept

DOM is Document Object Model.

Get element from DOM

document.getElementById(id); //return single object

// return multiple object and we reference by key
a = document.getElementByClassName(classname);
b = document.getElementByTagName(tag);
a[0].innerHtml = "Hello World";

we can change attribute of object with object notation..
a[0].innerHtml = "Hello World";
// .src , href, class, name, style..

Nodes

element.childNodes returns an array of  an element's child nodes.
element.firstChild returns the first child node of an element.
element.lastChild returns the last child node of an element.
element.hasChildNodes returns true if an element has any child nodes, otherwise false.
element.nextSibling returns the next node at the same tree level.
element.previousSibling returns the previous node at the same tree level.
element.parentNode returns the parent node of an element.

Creating Elements



Use the following methods to create new nodes:
element.cloneNode() clones an element and returns the resulting node.
document.createElement(element) creates a new element node.
document.createTextNode(text) creates a new text node.

Place element in DOM

element.appendChild(newNode) adds a new child node to an element as the last child node.
element.insertBefore(node1, node2) inserts node1 as a child before node2.

Removing Node


parentElement.removeChild(node);
To remove node first we have to select parent node. then call removeChild() method

Replace Child

 parentElement.replaceChild(newNode, oldNode)

Reference : sololearn.com

Share this

Related Posts

Previous
Next Post »