Navigating a nested list - jQuery

I am currently doing a DOM traversal with jQuery, I am trying to select each item one #treeListat a time when I click the button, but as soon as it goes through the second list #innerList, it will select all the items in this list and continue to click through the list. How to proceed #innerListwith #treeList?

$("#MoveDown").click(function() {
  $('.parentStyle + li, li:eq(0)')
    .last()
    .addClass('parentStyle').siblings('li')
    .removeClass('parentStyle');
});
    .parentStyle {

      background-color: #F99;

    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <ul id="treeList">
    <li class="parent">Aunt Grace</li>
    <li class="parent">Mother Joan</li>
    <li class="parent">Father Joe
      <ul id="innerList">
        <li class="child">Son John</li>
        <li class="child">Son James</li>
        <li class="child">Daughter Aine</li>
      </ul>
    </li>
    <li class="parent">Uncle Tom</li>
    <li class="parent">Aunt Jen</li>
  </ul>
</div>

<button id="MoveDown">Move down</button>
Run code
+4
source share
1 answer

I'm not 100% about how you want the workaround to work, but I'm going to hit him with this assumption:

, , , - LI, UL (lvl 0). LI UL (lvl1), - (lvl 1), LI (lvl 0).

, :

$('.clickit').click(function() {
    var level = 0;
    var $list = $('#treeList');
    traverseList($list, level);
});

function traverseList($list, level) {
    if ($list.length > 0) { 
        $list.children('li').each(function() {
            $(this).prepend(level);
            if ($(this).children('ul')) {
                traverseList($(this).children('ul'), level + 1);
            }
        });
    }
}

Fiddle : http://jsfiddle.net/xhh4wqv7/1/

. , , . , 1 1 , .

index(), , . , . , node , .closest('li') .

:

$("#MoveDown").click(function () {
    var $tree = $('#treeList');
    var $li = getLi($tree);
    $tree.find('li').removeClass('parentStyle');
    $li.addClass('parentStyle');    
});

function getLi($tree) {
    var $li = $tree.find('.parentStyle').last();
    var $liList = $tree.find('li');
    var idx = $liList.index($li);
    if (idx < 0 || idx == $liList.length) { return $liList.first(); }
    else { return $liList.eq(idx + 1); }
}

Fiddle: http://jsfiddle.net/xhh4wqv7/4/

+2

All Articles