Getting hierarchical positions <ul> and <li> in jquery
I am trying to get how deep my nest is using jquery, and then create a string containing li and numbers, on how deep they are nested. For instance:
<ul> <li> MenuItem1 </li> <li> MenuItem2 <ul> <li> SubItemA </li> </ul> </li> <li> MenuItem3 </li> </ul> should create "0:MenuItem1 0:MenuItem2 1:SubItemA 0:MenuItem3" or at least something like that. Any ideas would be appreciated.
+4
1 answer
Sort of:
var text = $('li').map(function() { var num_parents = $(this).parents('ul').length; // or .parentsUntil('#someId', 'ul') if you have `$('#someID li')` above return (num_parents - 1) + ': ' + $(this).contents().map(function() { if(this.nodeType === 3) { return $.trim(this.nodeValue); } return null; }).get().join(''); }).get().join(' '); Depending on your actual HTML structure, you can also make it easier to extract the text of the li element in
return (num_parents - 1) + ': ' + $.trim(this.firstChild); if the text immediately follows the opening <li> .
Or, if you have other tags inside each li element (e.g. span or div ), and you also want to get their content, you can clone the current node and delete all ul descendants
var text = $.trim($(this).clone().find('ul').remove().end().text()); return (num_parents - 1) + ': ' + text; Link: map , parents , parentsUntil , contents , get
+5