OO programming with JQuery ... basic problems

Hello can someone tell me why this doesn’t work as expected?

$(document).ready( function() {

    var element = $("#myElement").get();
    element.myAttribute = "hello!";
    console.log("from initial:"+element.myAttribute);



function doFunction() {

    var element = $("#myElement").get();
    console.log("from function:"+element.myAttribute);



What are you expecting .get() to do, and what are you expecting to occur overall?

get() is a JQuery function that accesses the DOM element that has been wrapped in a JQuery object. At-least that’s how I understand it.


I expect the attribute assigned to that object to remain permanent, not just local to the function where it is assigned.

Thanks for your help.

Have a look at the .data() method

Ah … nice. That looks promising. I’ll have a play with it tomorrow and see where I get.

I wonder though, is the problem in my example intrinsic to the get() method? Because in non-JQuery JavaScript, doing similar should give the expected results, shouldn’t it?

It’s partly an understanding issue.

The .get() method gives you an array of elements, so your code is assigning the myAttribute property on to a temporary array of elements, instead of an element itself.

If you indexed the zeroth element of that array, your attribute assignment would then work as you expect.

When working with jQuery, it’s commonly preferred to use the data method which not only simplifies usage, but also prevents against circular reference memory issues that some browsers have.

I’m not quite sure you’re correct there, although I’d be happy to be wrong.

I think that the get() method actually returns the first element in the array.

And besides that, from memory, I’ve tried it like $("#myElement)[0] and that doesn’t work either.

I don’t have my dev environment setup on the computer I’m on at the moment, so I can’t be bothered confirming that.

You can clear up your confusion without your development environment by going to the .get() documentation page and giving it a quick read.

The documentation says things like:

Without a parameter, .get() returns all of the elements


With an index specified, .get() will retrieve a single element

Please experiment and if need be, come back with sample code about any confusions that may remain.

Thanks mate, appreciated.