Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a good way to attach JavaScript objects to HTML elements?

Tags:

javascript

dom

I want to associate a JavaScript object with an HTML element. Is there a simple way to do this?

I noticed HTML DOM defines a setAttribute method and it looks like this is defined for arbitrary attribute name. However this can only set string values. (You can of course use this to store keys into a dictionary.)

Specifics (though I'm mostly interested in the general question):

Specifically, I have HTML elements representing nodes in a tree and I'm trying to enable drag-and-drop, but the jQuery drop event will only give me the elements being dragged and dropped.

The normal pattern for getting information to event handlers seems to be to create the HTML elements at the same time as you are creating JavaScript objects and then to define event handlers by closing over these JavaScript objects - however this doesn't work too well in this case (I could have a global object that gets populated when a drag begins... but this feels slightly nasty).

like image 242
user47741 Avatar asked Sep 09 '09 23:09

user47741


People also ask

Can JavaScript add HTML elements?

Using the innerHTML attribute: To append using the innerHTML attribute, first select the element (div) where you want to append the code. Then, add the code enclosed as strings using the += operator on innerHTML.

Should you use objects in JavaScript?

Using objects is great because you can add methods. Methods are functions that are linked to the data within your object. This makes it much easier to work with objects.

How can JavaScript using objects?

JavaScript is designed on a simple object-based paradigm. An object is a collection of properties, and a property is an association between a name (or key) and a value. A property's value can be a function, in which case the property is known as a method.


2 Answers

JavaScript objects can have arbitrary properties assigned to them, there's nothing special you have to do to allow it. This includes DOM elements; although this behaviour is not part of the DOM standard, it has been the case going back to the very first versions of JavaScript and is totally reliable.

var div= document.getElementById('nav'); div.potato= ['lemons', 3]; 
like image 119
bobince Avatar answered Sep 20 '22 03:09

bobince


Have you looked at the jQuery data() method? You can assign complex objects to the element if you want or you can leverage that method to hold a reference to an object (or some other data) at the very least.

like image 28
Phil.Wheeler Avatar answered Sep 19 '22 03:09

Phil.Wheeler