Search code examples
javascripthtmlyui

Getting index of a node on click


I'm trying get the index of a tab in YUI using delegate along with the indexOf method - specifically I want to remove a tab on the click of an image housed inside of an li element:

var tabView = new Y.TabView({
    srcNode: '#data-table'
});
...
//creating tabs
...
var removeTab = function(e) {
    var tabList = e.container.all('li'); //returns a list of the 'li' elements/tabs
    tab = tabView.indexOf(e.currentTarget);
    alert(tab); //returns -1 (node not found)   
    //tabView.remove(tab);         
}
Y.one('#data-table').delegate('click', removeTab, 'img');//on click of the img, launch removeTab

I don't believe YUI has a simpler way of doing this-most guides I've found are outdated or don't implement removing tabs the same way.


Solution

  • The problem is that the delegate handler is set on img element - so e.currentTarget will refer to an <img> element (that was clicked).

    With e.container.all('li'), however, you retrieve the collection of <li> elements. No element in this collection, naturally, can be equal to <img>. That's why indexOf fails.

    One possible solution is finding the <li> parent of <img> element first, then check its index:

    var liClicked = e.currentTarget.ancestor('li');
    var tabIndex  = tabList.indexOf(liClicked);