JQuery Dynatree - search node by name

JaSmin picture JaSmin · Sep 5, 2012 · Viewed 8.6k times · Source

I would like to start using Dynatree on my page, however I will probably need searching my tree by name. Do you know maybe how to do this?

Answer

JaSmin picture JaSmin · Oct 2, 2012

I needed to have not only matching nodes, but also the whole paths to these nodes. I wrote this functionality and it works for me.

Modifications for library:

var clear = true;

DynaTreeNode.prototype.search = function(pattern){

    if(pattern.length < 1 && !clear){
        clear = true;
        this.visit(function(node){
            node.expand(true);
            node.li.hidden = false;
            node.expand(false);
        });
    } else if (pattern.length >= 1) {
        clear = false;
        this.visit(function(node){
            node.expand(true);
            node.li.hidden = false;
        });

        for (var i = 0; i < this.childList.length; i++){
            var hide = {hide: false};
            this.childList[i]._searchNode(pattern, hide);
        }
    } 
},

DynaTreeNode.prototype._searchNode = function(pattern, hide){

    if (this.childList){
        // parent node

        var hideNode = true;
        for(var i = 0; i < this.childList.length; i++){
            var hideChild = {hide: false};
            this.childList[i]._searchNode(pattern, hideChild);
            hideNode = hideNode && hideChild.hide;
        }
        if(hideNode && !this._isRightWithPattern(pattern)){
            this._hideNode();
            hide.hide = true;
        } else {
            hide.hide = false;
        }

    } else {
        // leaf
        if (!this._isRightWithPattern(pattern)){
            this._hideNode();
            hide.hide = true;
        } else {
            hide.hide = false;
        }
    }
},

DynaTreeNode.prototype._isRightWithPattern = function(pattern){
    if((this.data.title.toLowerCase()).indexOf(pattern.toLowerCase()) >= 0){
        return true;
    }
    return false;
},

DynaTreeNode.prototype._hideNode = function(){
    if(this.li) {
      this.li.hidden = true;
    }
}

Use:

$("tree").dynatree("getRoot").search(pattern);