views:

244

answers:

2

Hi, It is in my understanding that referencing any DOM element in jQuery via the dollar sign (like this: $("#mydiv")), returns an object.

I am looking to add an additional property to an object as such:

$("#mydiv").myprop = "some value";

but this does not seem to work. I am trying to store a value in this object so I can reference it later.

The following code, though, gives me an undefined value even immediately after I set the property.

$("#mydiv").myprop = "some value";
alert($("#mydiv").myprop);

this code does not work either:

$("#mydiv")["myprop"] = "some value";
alert($("#mydiv").myprop);

Is there a way to achieve this? Or do I need to store all my properties as attributes on the DOM object via $("#mydiv").attr("myprop", "some value") (this is much less desirable).

Thanks!

+1  A: 

The $ function creates a jquery object that represent a dom element. You can change the attributes of the object, but those changes won't be made aparent in the element it "represents" unless jquery knows what to do with them (assigning a click event handler perhaps).

So when you make the first selection, it modifies the object you made, but doesn't do anything to the actual html element. When you run $ again, it creates a SEPARATE object, that does not retain the attribute change you made to the first.

you may be able to make a direct change to an html object: (without jquery)

getElementByID("theid").myprop = "hello world";

resulting in: <p id="theid" myprop="hello world"></p> but setting an attribute of a jquery object just won't do it. To get the equivalent effect in jquery, use the .data method that Ken Browning suggested. (too late again...) :D

CrazyJugglerDrummer
thank you very much. this is good to know but not quite what i was looking for. votes up, though.
yuval
+12  A: 

jQuery exposes the concept of a property-bag with the data method.

// set some arbitrary data
$('#selector').data('example-property', exampleValue);

// get the value later
var theValue = $('#selector').data('example-property')

This avoids DOM manipulations which can be expensive in terms of performance.

Ken Browning
ooohhh....nice.
seth
thank you very much! that's exactly what i was looking for! :)
yuval