beyondit01 beyondit01 - 6 months ago 9
jQuery Question

Generating a nodes path from an unordered list

I have the following list of data:

enter image description here

Which is set up with this HTML:

<ul id='tree'>
<li data-id="1" data-parent="0">
Home
<ul>
<li data-id="2" data-parent="1">
About
<ul>
<li data-id="4" data-parent="2">
What we do
</li>
</ul>
</li>

<li data-id="3" data-parent="1">
Contact
<ul>
<li data-id="5" data-parent="3">
Employees
<ul>
<li data-id="6" data-parent="5">
Full-time
</li>

<li data-id="7" data-parent="5">
Part-time
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>


Upon clicking a button, I want to generate the node path for each list item and add it to a string of data I can format.

I have started with this:

$('button').on('click', function(){

var output = "";

$("ul#tree li").each(function(){
var id = $(this).data("id");
var parent = $(this).data("parent");
output = output + "id=" + id + "&parent=" + parent + "$";
});

$("section").html(output);

});


Which generates:

id=1&parent=0
id=2&parent=1
id=4&parent=2
id=3&parent=1
id=5&parent=3
id=6&parent=5
id=7&parent=5


However, I want to add the node path of each line (the path of parent ID's to the current list item). So, for example, it would look like this:

id=1&parent=0&node_path=.0.
id=2&parent=1&node_path=.0.1.
id=4&parent=2&node_path=.0.1.2.
id=3&parent=1&node_path=.0.1.
id=5&parent=3&node_path=.0.1.3.
id=6&parent=5&node_path=.0.1.3.5.
id=7&parent=5&node_path=.0.1.3.5.


I'm not sure how to create a function that would combine parent ID's in the path of ul > li's...

Answer

You could use parents(), to get the list of parents. You could take this further and get rid of the parent data attribute all together, which would simplify the following code.

$('#mybutton').on('click', function () {

     var output = "";

     $("ul#tree li").each(function () {
         var id = $(this).data("id");
         var parent = $(this).data("parent");
         output = output + "id=" + id + "&parent=" + parent  + "&node_path=";

         var node_path = parent + ".";
         $(this).parents('li').each(function() {
             node_path +=  $(this).data("parent") + ".";
         });
         output += node_path.split('').reverse().join('')
         output += "<br/>";
     });

     $("#mysection").html(output);

 });

http://jsfiddle.net/4t6jgzhu/