For example, when processing events, sometimes you need to know which child node is currently clicked, but the HTML DOM itself does not directly provide the corresponding attributes, so you need to calculate it yourself.
From an index number, it is easy to get the child node or child element corresponding to the index. Just use parentNode.childNodes[index] or parentNode.children[index] directly.
But conversely, knowing a node or element object is not so straightforward to know its index number.
For some special elements, HTML DOM has corresponding attributes indicating their index numbers, mainly the TD and TR elements of tables.
Table cell TD element has cellIndex attribute.
The table row TR element has a rowIndex attribute.
If your processing target happens to be a table, use these two attributes first.
But general nodes or elements do not have attributes such as childNodeIndex or childElementIndex.
Solutions are mainly divided into two categories:
1. Pre-calculate and cache the index number of the node (can be stored in node attributes or js variables).
2. Real-time calculation requires traversing some nodes.
In application, one of the above two types of solutions can be selected according to different actual situations.
Scenarios where option 1 is applicable:
When the DOM structure will not change and the index of individual nodes needs to be obtained frequently, option 1 can be used.
The advantage is that subsequent reading is fast, but the disadvantage is that initialization requires overhead and needs to be re-initialized after the DOM structure changes.
Situations where option 2 is applicable:
The DOM structure may change, and the index of individual nodes is not obtained particularly frequently, option 2 can be used.
The advantage is that it is not affected by DOM structure changes, does not pollute the DOM structure, and has no initialization overhead. The disadvantage is that it is not suitable for high-frequency calls.
Generally speaking, it is better to adopt option 2, because usually the size of the DOM tree is relatively limited, and one cycle of loops will not significantly reduce the overall performance, and its advantages are significant.
For IE browser, there is a more direct method.
From IE4 to IE11, there is a sourceIndex attribute. This attribute represents the order of the elements in the DOM tree. Comparing the difference in the sourceIndex of the element and the parent element makes it easy to know which child element the element is.
I wrote a function to differentiate the processing. Under IE, sourceIndex is used for efficient judgment, while for non-IE, general traversal is used.