Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I assign a property to a jQuery object?

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!

like image 278
Yuval Karmi Avatar asked Jul 30 '09 00:07

Yuval Karmi


3 Answers

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.

like image 94
Ken Browning Avatar answered Oct 19 '22 04:10

Ken Browning


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

like image 44
Gordon Gustafson Avatar answered Oct 19 '22 05:10

Gordon Gustafson


I'm not sure wether or not this is due to a change in jQuery. But I've done it pretty much as described in the question...

var domElem = $('#selector');
domElem.myProp = "Hello world";

Now in my case I have to use this object in a method call later on:

<span onclick=\"SelectAll(domElem)\">Click me!</span>

The method can then do like this:

function SelectAll(domElm){
    alert(domElm.myProp);
}

As I said - it might be an update in the jQuery engine, but it seems that the .data() call is no longer needed :-)

like image 1
woodbase Avatar answered Oct 19 '22 04:10

woodbase