How to set unique values to elements in DOM without displaying it user in Inspector?

I was wondering whether is there any way to set unique values to elements to DOM Nodes using Javascript?

I know about using data-* attribute but that will make the value within that attribute visible in Inspector Tools of browser.

Yes there is. You can use setAttribute to set values on DOM elements.

el.setAttribute("someName", "someValue");
// <div someName="someValue"></div>

And you can use getAttribute to retrieve the value.

console.log(el.getAttribute("someName"));
// "someValue"

However, the “without it displaying in user inspector” is a completely different situation, which doesn’t seem to be achievable.

Isn’t there a way to mapping a unique value to specified element and storing it on memory for temporary basis?

Hi Paul, how about setting it as a custom property of the node? I guess it can still be found through the inspector that way, but it will not be as visible as an attribute. Just a thought…

Yes, with Symbols you can use a node element as a key to refer to information. If you’re okay with storing information outside of the DOM then that’s one way to do it.

All element properties are available via the inspector, in the Properties tab.

Can you guide me please on how to set these “Symbols” and retrieve them?

And by setting these values they will not visible anywhere in Inspector tools right?

You can use the node as a key to retrieve information from a map.

For example:

<div id="div1"></div>
<div id="div2"></div>
var map = new Map();
map.set(div1, "testvalue");

console.log(map.get(div1)); // testvalue
console.log(map.get(div2)); // undefined

Well, you can output the map contents to the console. If you’re wanting completely hidden information that cannot be retrieved, then that can’t be done.

I would suggest to use a weak map though to avoid memory leaks after removing such an element from the DOM (or you’d have take care of removing the corresponding map entry yourself). If you happen to be using jQuery, another possibility would be its .data() method, which would also automatically free the memory as long as you’re using jQuery methods to remove the element as well.

If you’re taking the map approach then no, they won’t; the only way to retrieve that information would be by setting a breakpoint to a point in the code where you’d have access to the map variable… but as @Paul_Wilkins said, no information can be completely hidden.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.