Leben
Leben

Reputation: 33

Do HTML elements have 'hidden indexes' for the DOM?

For example, document.getElementsByClassName("whatever") returns a list of elements, and each element has an index (so the element x is the [3] in that list, for example).Do HTML elements save that index inside the element, somehow? Or they're 'unaware' of their position?

Example of the usage I'd do with that property:

You click an element with class "People", using event.target when onclick. So you want to know which position it has, in the 'People' list. Let's say it's event.target.classNameIndex. So once you know the index, you can do things in JavaScript.

Obviously the simple alternative I can think of this is simply picking event.target and searching it inside the getElementsByClassName list. Or simply giving IDs to all elements. But avoiding that would be nice.

Hope you understand my question. :)

Upvotes: 0

Views: 97

Answers (2)

Peter B
Peter B

Reputation: 24147

No, for lots of reasons.

First of all, you are doing a query on the internal DOM structure, and the DOM tree itself might change immediately after your query. Elements can be added, moved or removed.

Furthermore, two very different queries might have overlapping results. E.g. query 1 might return:

[ <div id="a">, <div id="b"> ]

While query 2 could return:

[ <div id="b">, <div id="c"> ]

(for simplicity I am representing the results as arrays)
In the above, how would the element <div id="b"> know its unique and unchanging "index", given the truly infinite amount of possible queries, not the mention the possibly variable DOM again?

Upvotes: 1

No

The elements are generated either dynamically or statically and are independent from everything done with them after being displayed. There are pure javascript ways of obtaining the index of an element in a array-like structure but they will most likely depend on the use of a element.onClick function and pairing them with other elements via some sort of selector.

Upvotes: 1

Related Questions