Search code examples
jqueryindexingparents

jQuery: Keep .index( ) to return every parents index


In the code below, I am trying to get back the index of the element clicked and if so, its parent index. The problem is that it tries to return, also, its parent's index...

By example: if I click on "1" the alert will give back 0,0 which is good. If I click on A2, the alert will return 0,1 (which is also good) and then return 1,0 (the parent "coordinate") !!! I want to keep it to return the parent array...

<ul>
    <li>1</li>
    <li>2
    <ul>
        <li>A2</li>
        <li>B2</li>
        <li>C2</li>
    </ul>
    </li>
    <li>3</li>
    <li>4</li>
    <li><5</li>
</ul>


$('#control ul li').click(function(e) { 
    e.preventDefault();

    var child = $(this).index(); // Get actual li element index
    var parent = $(this).parents('li').index(); // Get the later parent index
    if(parent === -1) { parent = 0; } // If it doesn't have a parent set -1 to 0
    var current = $.makeArray([child,parent]); // Make an array of the coordinate 

    alert(current);


    switcher(current);
});

Solution

  • You should stop the event propagation. Try this

    $('#control ul li').click(function(e) { 
       e.stopPropagation();
    
       var child = $(this).index(); // Get actual li element index
       var parent = $(this).parents('li').index(); // Get the later parent index
       if(parent === -1) { parent = 0; } // If it doesn't have a parent set -1 to 0
       var current = $.makeArray([child,parent]); // Make an array of the coordinate 
    
       alert(current);
    
    
       switcher(current);
    });