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);
doFunction();
});
function doFunction() {
console.log("Here!");
var element = $("#myElement").get();
console.log("from function:"+element.myAttribute);
}
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?
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.