Skip to content

Instantly share code, notes, and snippets.

@luk3thomas
Last active August 29, 2015 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luk3thomas/10260076 to your computer and use it in GitHub Desktop.
Save luk3thomas/10260076 to your computer and use it in GitHub Desktop.
Recursive function for creating a menu object. The function takes a jQuery object and recursively builds a menu tree
var _links = function($lis, depth) {
return $.makeArray($lis.map(function(i, li) {
var $li = $(li),
$a = $li.find('> a'),
$children = $li.find('> .sub-menu > li'),
link = {
name: $a.text(),
href: $a.attr('href'),
depth: depth
};
if($children.length) {
link.children = _links($children, depth + 1);
}
return link;
}));
};
var _indent = function(depth, indent) {
indent = indent || '   ';
var s = '';
for(i=0; i < depth; i++) {
s += indent;
}
return s;
};
var _options = function(el, i) {
if(el.children) {
var children = $.map(el.children, function(c, i){
return _options(c, i)
});
}
var main = ['<option value="', el.href, '">', _indent(el.depth), el.name, '</option>'].join('');
return [main].concat(children || []).join('')
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment