Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I add arbitrary properties to DOM objects?

Tags:

javascript

dom

Can I add arbitrary properties to JavaScript DOM objects, such as <INPUT> or <SELECT> elements? Or, if I cannot do that, is there a way to associate my own objects with page elements via a reference property?

like image 699
Tony the Pony Avatar asked Nov 23 '10 16:11

Tony the Pony


People also ask

How do I add elements to my DOM?

To add a new element to the HTML DOM, you must create the element (element node) first, and then append it to an existing element.

What can a DOM element contain?

The DOM is the way Javascript sees its containing pages' data. It is an object that includes how the HTML/XHTML/XML is formatted, as well as the browser state. A DOM element is something like a DIV, HTML, BODY element on a page. You can add classes to all of these using CSS, or interact with them using JS.

What are the properties of DOM in JavaScript?

In the DOM, all HTML elements are defined as objects. The programming interface is the properties and methods of each object. A property is a value that you can get or set (like changing the content of an HTML element). A method is an action you can do (like add or deleting an HTML element).


1 Answers

ECMAScript 6 has WeakMap which lets you associate your private data with a DOM element (or any other object) for as long as that object exists.

const wm = new WeakMap(); el = document.getElementById("myelement"); wm.set(el, "my value"); console.log(wm.get(el)); // "my value" 

Unlike other answers, this method guarantees there will never be a clash with the name of any property or data.

like image 125
James Avatar answered Oct 12 '22 00:10

James