I want to know how can I save a reference to an object (this) using jquery. what I mean is for example I want when my user clicked on any element in his page, I send the reference of object to my webserver, and next time user calls the server, I send back the saved refernce to browser, and do other stuff like fadeIn() ... so far I've tried using JSON.stringify(this) and JSON.stringify($(this)), but both dont seem to work. I also tried saving elemen't ID and class and type, so next time user calls them I could just use selectors, but since I wan to use the script on any website, things might not be the ideal to use selectors. is there any way to get the exact refernce to an element and send it to server ?
While I do not think that there is a way to do exactly what you ask, I would suggest placing an ID on the elements you wish to save in this manner. You can then save and later retrieve that ID from the server using ajax.
Your selector would look something like this:
var saveId = $(this).attr('id');
I do not believe that this will work on "any web site" as you have indicated, but if you control the site, you can make sure all the elements you DO wish to save have an ID and given that all ID's on a page must be unique, you should be able to acomplish this - within that contraint.
You can save selector field so that you can used to select it later. Like this:
var Elements = $('body').find('.container').find('div.controls'); // Just some complex selection
...
var ToSave = Elements.selector;
AJAXSave('Elements', ToSave);
// ToSave will be 'body .container div.controls' which is the elements we are talking about.
...
var LastElements = $(AJAXLoad('Elements'));
Nope, references to DOM elements only work within the one DOM instance (so even if you reload the same page, references won't work anymore). You will have to use selectors. If you're sure that the page structure doesn't change, the easiest way to get the same element is this:
// Get numeric index of element on page.
var index = $('*').index(this);
// Restore element.
var $this = $('*').eq(index);
You can make it safer from the page changing by using IDs and classes where possible.
Have a look at this script: http://paste.blixt.org/297640
Here's a simpler version of it that doesn't rely on classes/IDs:
jQuery.fn.getPath = function () {
if (this.length != 1) throw 'Requires one element.';
var path, node = this;
while (node.length) {
var realNode = node[0], name = realNode.localName;
if (!name) break;
name = name.toLowerCase();
var parent = node.parent();
var siblings = parent.children(name);
if (siblings.length > 1) {
name += ':eq(' + siblings.index(realNode) + ')';
}
path = name + (path ? '>' + path : '');
node = parent;
}
return path;
};
Used like this:
// Get selector for element.
var path = $(this).getPath();
// Get element using selector.
var $this = $(path);