Search code examples
javascriptdomecmascript-next

Proper Place to Bind Object to Element


Data Attributes are a safe place to store strings onto a DOM element, because you're guaranteed that your property-naming will never collide with a future property that gets added to the DOM specification.

However, what if you want to bind a non-JSON javascript object to an DOM element as a property?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Bind Custom Object to DOM Element</title>
    <style>
            div{ border: solid #333333 1vmin; padding:1vmin; 
                display:inline-block; font-size:4vmin}
    </style>
    <script type="text/javascript">
        function main()
        {
            let obj = {}
            obj.name = "Lonnie";

            let div = document.createElement("div");
            div.textContent = "Click Me";
            div.myCustomObject = obj;
            div.addEventListener('click',function()
            {
                alert(this.myCustomObject.name);
            });
            document.body.appendChild(div);
        }
        window.addEventListener('load', main);
    </script>
</head>
<body>
</body>
</html>

Data attributes are designed to hold strings, not objects. Is it ok to use them for nonJSON object-properties, or does the specification recommend a different location for adding object-properties to DOM nodes?


Solution

  • Data attributes are designed to hold strings, not objects.

    But you are not using attributes. Therefore you can store everything you want under a regular property.

    Is it ok to use them for nonJSON object-properties,

    Sure.

    or does the specification recommend a different location for adding object-properties to DOM nodes?

    No, it does not. the DOM spec is language neutral, therefore it doesn't really describe how objects in JS behave that implement that spec.