[whatwg/dom] Proposal: Element.elementIndex, Node.nodeIndex (#546)

The Element.elementIndex property returns integer value indicating the position of the element relative to its adjacent elements.

The Node.nodeIndex property returns an integer value indicating the position of the node relative to its adjacent nodes, except comment nodes.

### Syntax
<pre>
Element.elementIndex;
Node.nodeIndex;
</pre>

### Example
<pre>
&lt;ul&gt;
    &lt;li&gt;item 1&lt;/li&gt;
    &lt;li&gt;item 2&lt;/li&gt;
    &lt;!-- comment --&gt;
    &lt;li id=&quot;el&quot;&gt;item 3&lt;/li&gt;
    &lt;li&gt;item 4&lt;/li&gt;
    &lt;li&gt;item 5&lt;/li&gt;
&lt;/ul&gt;
</pre>

<pre>
el.elementIndex; // return 2
el.nodeIndex;    // return 6 (elements + text nodes before each tags)
</pre>

### Implementation
If the element is not part of the HTML DOM - should both functions return 0 or null?

<pre>
Object.defineProperty(Element.prototype, 'elementIndex', {
    enumerable: false,
    configurable: false,
    get: function() {
        if (!this.parentNode) {
            return null;
        }

        var i = 0, el = this;

        while (el = el.previousElementSibling) {
            i++;
        }
        return i;
    },
});
</pre>

<pre>
Object.defineProperty(Node.prototype, 'nodeIndex', {
    enumerable: false,
    configurable: false,
    get: function() {
        if (!this.parentNode) {
            return null;
        }

        var i = 0, el = this;

        while (el = el.previousSibling) {
            // exclude comment nodes???
            el.nodeType != 8 && i++;
        }
        return i;
    },
});
</pre>

### Rationale
The possibility of finding the index without using loops or by bending functions of array in own helper functions.

-- 
You are receiving this because you are subscribed to this thread.
Reply to this email directly or view it on GitHub:
https://github.com/whatwg/dom/issues/546

Received on Sunday, 17 December 2017 16:12:21 UTC