0

I'm wondering why this method:

window.location.hash = JSON.stringify($("body")[0]);

Adds some kind of jquery-id to the hash. It looks like this:

foo.htm#{"jQuery18305139440292647334":13}

What is this "id" (how is it called?) and is there any way to get back to the DOM element from this id? Is this id consistent after page reload?

Jan Hommes
  • 5,122
  • 4
  • 33
  • 45

1 Answers1

1

Your problem is that JSON.stringify() isn't really fit to serialize DOM elements or any other circular structure (like a jQuery object).

Apart from that, JSON.stringify() is a browser specific function. You obviously tested your code in firefox, because if you try to do the same in chrome you will get no output.

There is some more information you might find useful over here: How to serialize DOM node to JSON even if there are circular references?

As for the question why you get the random number, that's just some firefox under-the-hood magic if you ask me. Main point is, what you are trying to do is not supported or documented, and will probably always have unexpected results.

I'm also not sure what you are trying to do, but if you are planning to reference a specific DOM element from your URL's hash-tag, consider just adding the jQuery selector.

window.location.hash = encodeURIComponent('body:first');
// wil result in URL like: http://foo.htm#body%3Afirst

And then after the page loads with a hash, you can retrieve the element like this:

var myjQueryObject = $(window.location.hash);
Community
  • 1
  • 1
Jules Colle
  • 11,227
  • 8
  • 60
  • 67