7

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);
            });
    });
Paul
  • 6,572
  • 2
  • 39
  • 51

3 Answers3

9

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/

Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307
0

This is pretty hacky, but you can always use Array.prototype's indexOf...

Array.prototype.indexOf.call(list-o-children, elem-to-find)
zenazn
  • 14,295
  • 2
  • 36
  • 26
-1

MooTools Element.getAllPrevious returns all sibling elements before the current element, the length of previous siblings equals to the index of the current element.

var index = rowElem.getAllPrevious('div.Row').length;
AHHP
  • 2,967
  • 3
  • 33
  • 41
  • Hi, even though this code may be the answer to the question, it's important to add some context to the answer to improve its quality, so add it if you can. You can check more answering tips here [How to answer](https://stackoverflow.com/help/how-to-answer) – fmaccaroni Nov 18 '20 at 14:11
  • 1
    For MooTools users, the code and function usage is clear; btw I added some notes. – AHHP Nov 18 '20 at 14:33