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

3

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);
            });
    });
Pion answered 18/8, 2011 at 4:34 Comment(0)
C
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/

Clubbable answered 18/8, 2011 at 4:54 Comment(0)
L
0

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

Array.prototype.indexOf.call(list-o-children, elem-to-find)
Lanceted answered 18/8, 2011 at 4:46 Comment(0)
C
-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;
Colonel answered 18/11, 2020 at 11:46 Comment(2)
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 answerBlazon
For MooTools users, the code and function usage is clear; btw I added some notes.Colonel

© 2022 - 2024 — McMap. All rights reserved.