We help IT Professionals succeed at work.
Get Started

Loop through a UL

tonelm54
tonelm54 asked
on
128 Views
Last Modified: 2015-04-13
Im trying to do is write a tree plugin for jQuery as a bit of an exercise but running short on documentation.

What Im trying to do is go through all the first li items and if I find a ul  as a child than recursive go through, however my code just seems to be caught in a loop constantly calling the first ul.

HTML:-
<div id="testTree">
    <ul>
        <li>File</li>
        <li>Edit</li>
        <li>Help
            <ul>
                <li>Topics</li>
                <li>Search</li>
                <li>About</li>
            </ul>
        </li>
    </ul>
</div>

Open in new window


JQuery Code:-
(function ($) {
    'user strict';
    $.fn.makeTree = function () {
        DrawBranch($("ul"));
    };

    function DrawBranch($ulBranch) {
        $("ul:first() li").each(function (index) {
            console.log($(this).text());
            if ($(this).find('ul').length > 0) {
                console.log("children found");
                DrawBranch($(this).find('ul'));
            }
        });
    }
})(jQuery);

$(document).ready(function () {
    $('#testTree').makeTree();
});

Open in new window


What I believe it should be showing in alert boxes is:-
File
Edit
Help
Children Found
Topics
Search
About

However what is happening is its just looping:-
File
Edit
Help
Topics
Search
About
children found
File
Edit
Help
Topics
Search
About
children found
File
Edit
Help
Topics
Search
About
children found
File
Edit
Help
Topics
Search
About
children found
File
Edit
Help
Topics
Search
About
children found
.....etc

Im a bit confused, cause as far as Im concered it should be working ok, so a bit stuck before moving onto drawing the tree parts

Does anyone have any suggestions on looping through unordered lists?
Comment
Watch Question
CERTIFIED EXPERT
Most Valuable Expert 2013
Awarded 2012
Commented:
This problem has been solved!
Unlock 1 Answer and 3 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE