This simple algorithm finds any tag regardless of its type. However, for building your own DOM tree, you only need to consider the start tags. An end tag is nothing more than an indicator marking the end of an element. This means that the content following the closing tag of a given element can only be part of this element's parent node or its descendants. Let's have a closer look at the process of building a tree.
Every tree has a single root node, which forms the base of the tree.
As we want to create a method to write into an element, we have this root point already. What we actually need to do is build a smaller sub-tree inside the document's complete tree and consider the element we're gonna write into as the root node of this tree. In terms of computer science, this process is called scanning . This scanning happens in a linear fashion, from left to right. If we consider the string as a two-dimensional object, our task is to add another dimension in height, thus expressing the different levels of the tree.