Search code examples
javascriptmootools

Mootools get the child-index of an element from its parent


I am using event delegation in mootools. I want to know the row number that has been clicked. My solution is shown in this jsfiddle: Is there a better way than what I am currently doing?

My approach was to compare the elements until i found the match. Is there an IndexOf method I could use?

(The following is the data from the jsfiddle for the future)

HTML:

<div id="Record_List">
    <div class="Row">
        <input type="submit" name="Row" value="Edit"/>
    </div>
    <div class="Row">
        <input type="submit" name="Row" value="Edit"/>
    </div>
</div>

Javascript:

window.addEvent(
    'domready',
    function()
    {
        $('Record_List').addEvent(
            'click:relay(input)',
            function(evt, target)
            {
                evt.stop();

                var rowElem = target.getParent();
                var rowNumber = -1;

                $('Record_List').getChildren('div.Row').each(
                    function (el, num)
                    {
                        if (rowElem === el)
                        {
                            rowNumber = num;
                        }
                    });

                // Find the position of the row and display it here:
                alert('Row number: ' + rowNumber);
            });
    });

Solution

  • The type (Elements) returned by getChildren contains Array methods, including indexOf. MooTools will provide an implementation of that method if it does not exist for the browser. With that in mind, you could write:

    $('Record_List').getChildren('div.Row').indexOf(rowElem);
    

    Updated example: http://jsfiddle.net/andrewwhitaker/uJarB/