Traversing DOM using JavaScript
The HTML DOM defines a standard way for accessing and manipulating HTML documents.
The DOM presents an HTML document as a tree-structure expressed as an XML document.
DOM is a language independent API, as it can be used in Java, .NET, JavaScript and many more. I will use it with JavaScript to for my sample code provided below.
When talking about DOM trees , you are really talking about a hierarchy of nodes. These are some objects Inside XML(XHTML,HTML) document :
document - is very top level node wich contains all other nodes
element - represents the contents of a start tag and end tag
Attr — Represents an attribute name-value pair
Text — Represents plain text in an XML document contained within start and end tags or inside of a CData Section
CDataSection — The object representation of <![CDATA[ ]]>. This node type may contain any symbols including quotes.
To manipulate this obects i.e makes changes in XML(XHTML, HTML) we have some properties and methods:
nodeName - The name of the node
nodeValue - The value of the node
nodeType - One of the node type constant values
ownerDocument – Pointer to the document that this node belongs to
firstChild - Pointer to the first node in the childNodes list
lastChild – Pointer to the last node in the childNodes list
childNodes – A list of all child nodes
previousSibling – Pointer to the previous sibling; null if this is the first sibling
nextSibling – Pointer to the next sibling; null if this is the last sibling
hasChildNodes() – Returns true when childNodes contains one or more nodes
attributes – Contains Attr objects representing an element’s attributes; only used for Element nodes
appendChild(node) - Adds node to the end of childNodes
removeChild(node) - Removes node from childNodes
replaceChild (newnode, oldnode) – Replaces oldnode in childNodes with newnode
insertBefore (newnode, refnode) — Inserts newnode before refnode in childnodes
Let’s do some example to demonstrate functions and properties mentioned before.
Adding nodes using DOM:
In idex.html we have form tag with textarea and submit button inside
<body>
<form action=”#”>
<p>
<textarea rows=”5″ cols=”30″>
</textarea>
<br/>
<input value=”Add Text” />
</p>
</form>
</body>
In script.js addNode() function is triggered on form submit it gets value of textarea, creates text node then paragraph tag and appends all these
as child of body tag.
window.onload=initAll;
function initAll()
{
document.getElementById(“form1″).onsubmit=addNode;
}
function addNode()
{
var inText=document.getElementById(“textarea”).value;
var newText=document.createTextNode(inText);
var newGraf=document.createElement(“p”);
newGraf.appendChild(newText);
var docBody=document.getElementsByTagName(“body”)[0];
docBody.appendChild(newGraf);
return false;
}
It’s really well done! Respect to author.