how to create a tree containing some data, in javascript
===

 
In a web page with multiple HTML elements, including nested elements, the user is selecting some content.

I understand how to extract different attributes of each HTML Node- eg. ID, nodeType, nodeValue, text (in case of text nodes) and link value (ie 'href' attribute of links)... I also understand how to extract all the nodes corresponding to which some content has been selected by the user...

Now I want to store all this information in a tree structure... Each node in the tree will have many attributes. Also, I dont know beforehand how many levels deep the tree will be, or how many nodes will be there in it...

What is the best way to create such a tree structure?  

 

For example , a fragment of a HTML web page is given below--

<body>
    <div id="divText">Text 1
        <div id="divText1_1">Text 1_1</div>
        <div id="divText1_2">Text 1_2</div>
   </div>
 ...............
 ...............


In the same manner as above, if user selects text belonging to different divs/tables/lists I want to be able to store details for each such text selections in a tree.

For each element in the tree, I want to store the following attributes--

     NodeName
     NodeType
     NodeValue
     Text Content (if applicable)
     Href Attribute(if applicable)
     Name of HTML Element(if available)
     ID of HTML Element (if available/applicable)
     Location of selected content within the list or table (if the content is in a list or table)


Now if user selects the text "Text 1_1" from the HTML web page for which I have provided a fragment, I want to create a tree, root level element is 'body', then one level below is 'divText' and one more level below is 'divText1_1' (this is the div from which user has selected text)... After that, there is one more node consisting of the text "Text 1_1" (this is the text that the user has selected)...

So for this example, the tree should look like this-- 

    {
    "element":"body",
    "id":NA,
    "children":[
        {
            "element":"div",
            "id":divText,
            "children":[
                {
                    "element":"div",
                    "id":divText1_1,
                    "children":[
                     {
                            "element":"text",
                             "id":NA,
                            "text": Text 1_1
                     }    ],
                }   ],
          }
       ]
    }

With ref to the second part of my question, is the correct way creating a js object, and then using JSON.stringify? Or do I have to do something else?