I am trying to associate some "private" data with DOM elements. Rather than adding that data to the DOM element itself (I'd like to avoid changing the DOM element), I have a separate data object that I want to use as a map.
Rather than:
document.GetElementById('someElementId').privateData = {};
I want to do
internalPrivateDataMap[document.GetElementById('someElementId')].privateData = {};
Not all the elements have an id field, and some are created dynamically, so I can't use the id as the key.
This works fine for most elements, but for "a" elements, the key being used seems to be the href of the element, I think because the DOM defines a toString() function for a elements.
The result of this is that if I have two "a" elements with the same href, they are sharing privateData, which I don't want.
My current workaround is to generate an internal uniqueID I can use as a key, but that requires me to modify the DOM element, which I am trying to avoid.
Introduction to JavaScript Map object A key of an object must be a string or a symbol, you cannot use an object as a key. An object does not have a property that represents the size of the map.
DOM and JavaScript The document as a whole, the head, tables within the document, table headers, text within the table cells, and all other elements in a document are parts of the document object model for that document. They can all be accessed and manipulated using the DOM and a scripting language like JavaScript.
Map Keys. Maps accept any data type as a key, and do not allow duplicate key values.
To check if a key exists in a Map , call the has() method on the Map , passing it the name of the key as a parameter. The has method returns true if the specified key exists in the Map , otherwise it returns false .
As you noticed, this doesn't work reliably and I know no way to make it work without either giving every element a (generated) ID or at least assign a unique ID to a new custom element field; DOM nodes simply don't have the necessary properties to work as keys in a map.
So you really have these solutions left:
element.data()
to read and put private data into a DOM elementelement.privateData = {};
Note that you still need cleanup for event handlers which keep references to the element or you will have unexpected memory leaks.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With