Search code examples
javascriptjqueryjstreejtree

How to associate/fetch data to a jtree node


I have inline html data as below which renders fine in the browser without any errors.

<li id="node_1" test="testing">Node Name
  <data name="name" type="string" value="Steve"/>
  <data name="job" type="string" value="Developer"/>
  <data name="age" type="int" value="35"/>
</li>

I have the following JavaScript:

$('#jstree').on("changed.jstree", function (e, data)
{
  var node_id = data.node.id;
  var value = $("#"+node_id).attr("test");
  console.log(node_id);
  console.log(value);
});

I am able to access the attribute "test" added on the "li" node. But not sure how to access the child "data" nodes and get its property value

I found some pointers in link which uses json, but in my case I only have inline html data and at this moment I cannot switch to json. Please help.


Solution

  • Looking at the DOM structure I found that for every "li" node there is a subnode "a" created and the data structure I added appears as a child of "a" node and not "li" node

    DOM Structure - click for snapshot

    So from code we need to access the subnode "a" and get the children from the subnode as below...

    var properties = $("#"+node_id).find('a:first').children(".property");
    for(var i=0;i<properties.length;i++)
    {
      console.log($(properties[i]).attr("name"));
      console.log($(properties[i]).attr("value"));
    }
    

    Hope this helps others who may find themselves in a similar situation