DOM stands for the Document Object Model. Every HTML tag is the object, which have the different different properties which allow us to manipulate the DOM (HTML tag).
DOM represents the whole HTML page as a tree. This tree is made up of parent-child relationships, a parent node can have one or more child nodes.
<html> <head> <title>My Title</title> </head> <body> My Body </body> </html>
So the DOM tree of the above example is look like this.
So as you seen in the above image, the root element is the HTML and it have the 2 child node that is the HEAD and BODY. Where HEAD as the one more element TITLE and BODY element does not have any child element.
Where as the “My Title” and “My Body” becomes the Text Node, which is also one type of HTML node. Because every text internally have the text node.
<html> <head> <title>My Title</title> </head> <body> <p>Hello</p> <p>World</p> </body> </html>
What we think:
But it is wrong…
Yes, The result DOM tree is different than what we think. Because we wrote the HTML code like that.
In above example I wrote the new HTML tag in the new line, so here the one extra HTML tag is created for the new line, that is the Text Node which have the value white-space.
So be careful while traversing in the HTML node. If you put the white-space between HTML nodes or you wrote the new HTML nodes into the new line than you will get the one more text node with the value white space.
Above code is easy to write and easy to read, but it is vary hard to traversing with code. Every time we have to check the current node is the text node with the value white space than we have to take appropriate decision about it.
In above example I wrote the all HTML tags in one line, So there is no white-space or there is no new HTML tag in the new line.
Yes, the above code is difficult to read and difficult to write but it is vary easy to traversing with code.