Sheldon R.
Sheldon R.

Reputation: 452

Accessing FancyTree Node Data in JavaScript

I'm using FancyTree for the first time, and I would like define some custom node data, specifically an attribute named "content" in the HTML data used to create the tree:

    <li id="xxxx" data-content="true"  class="folder">

I have an init event-handler written in JavaScript and I want to access my custom data attribute there:

init: function(event, data, flag)
   {
    var tree = $("#tree").fancytree("getTree");
    node = tree.getNodeByKey(key);
    var data = node.data;

In an online tutorial, I saw that my custom attribute would be accessible as node.data.content, but I'm unable to display my custom attribute in an alert box to demonstrate that it was actually defined. How do I access my custom data attribute in my JavaScript function?

Sheldon

Upvotes: 2

Views: 11745

Answers (1)

IndieRok
IndieRok

Reputation: 1788

Ok, so i finally got it working. Your were close to getting your result.

The key variable is a string which represent the 'id' attribute of each LI element in your tree. You will obtain the node with that key. Once the node is obtained, you can retrieve your custom data attribute associated to that node. Since our 'data' variable is an object, containing key/value, you need to call it's 'key' name on the data object to retrieve the value, like so 'data.content'.

JS

$(function () {
    // using default options
    //Caching DOM element
    var $myTree = $("#tree").fancytree();
    // Get the DynaTree object instance
    var tree = $myTree.fancytree("getTree");
    //Set my key
    var key = "id1";
    //Get the node
    var node = tree.getNodeByKey(key);
    //Get the custom data attribute associated to that node
    var data = node.data;
    //data is an object so, data.content will give you the value of the attribute
    alert(data.content);
});

JSFIDDLE

Hope this helps!

Upvotes: 7

Related Questions