I have a nested unordered list populated by ajax and I am looking to create breadcrumb-style navigation out of it. The end result should be I click on any node in the list and the parent list items show up in the breadcrumb navigation.
<div id="list">
<ul>
<li class="expanded">
<a href="#" id="1122">Root Group</a>
</li>
<ul>
<li class="expanded">
<a href="#" id="1126">Northeast US</a>
</li>
<ul>
<li class="collapsed">
<a href="#" id="1127">Massachusetts</a>
</li>
<ul style="display: none; ">
<li class="expanded node">
<a href="#" id="1128">Mansfield-Foxboro</a>
</li>
<li class="expanded node">
<a href="#" id="1129">North Attleboro</a>
</li>
</ul>
<li class="expanded">
<a href="#" id="1144">New Hampshire</a>
</li>
<ul>
<li class="expanded node">
<a href="#" id="1145">Manchester</a>
</li>
</ul>
</ul>
<li class="expanded">
<a href="#" id="1181">Mid-Atlantic US</a>
</li>
<ul>
<li class="expanded">
<a href="#" id="1182">New York City</a>
</li>
<ul>
<li class="expanded node">
<a href="#" id="1183">Time Square</a>
</li>
</ul>
</ul>
</ul>
</ul>
</div>
So I click on New York City and I get:
Root Group > Mid-Atlantic US > New York City
I click on North Attleboro and I get:
Root Group > Northeast US > Massachusetts > North Attleboro
Is there a way to build this path using jQuery traversal?
You can start from the clicked
<a>element, use parents() to match the<ul>elements in its ancestor chain, then apply prev() to the result to obtain the immediately preceding<li>elements.From there, you can use find() to match the
<a>elements within the list items. If you add() the clicked hyperlink itself to the result set, you will have a jQuery object containing all the hyperlinks in the path, in the proper order.Now you only have to use map() to build an array of inner text values from the
<a>elements, along with Array.join() to concatenate a path string. The end result is something like:You can test it in this fiddle.