Can a DOM object be an index / key in a Javascript array?

I would like to save a map / hash of DOM objects. Can they serve as key objects? If not, what are the alternatives, please? If there are better ways - kindly credit them as well.

+4
source share
6 answers

You can put something as a key, but before actual use it is always converted to a string, and this string is used as a key. So, if you look at what domObject.toString() produces, you see that this is not a good candidate. If all your dom objects have an identifier, you can use this identifier. If not, and you still need a key based on the DOM object, you could probably use, for example, the _counter attribute with an automatic counter in the background, adding a new unique value to the DOM object if _counter is not already present.

+6
source

window already supports all DOM objects as properties. Instead of putting your own keys for each DOM object, try using a window or document object and methods that use an index based on the layout of the DOM tree.

+1
source

No, but you can set an attribute in a DOM element that contains a number that you would specify as an index in a numerically indexed array.

0
source

No, because object keys are strings.

You will have to β€œserialize” your objects using id or something else, and then search later. Probably not worth it, depending on what your real goal is.

0
source

The easiest way is to set the data attribute for an element.

0
source

Not exactly. But I think you want something like below. You can do with jquery ,

The .serializeArray() method creates an array of JavaScript objects, ready to be encoded as a JSON string. It works with a jQuery object representing a set of form elements. Form elements can be of several types

See the link below: http://api.jquery.com/serializeArray/

-2
source

Source: https://habr.com/ru/post/1388810/


All Articles