skip to Main Content

When I stringify a JQuery collection, it produces what appears to be a reference ID:

JSON.stringify($('.btn'));

> '{"0":{"jQuery360064998935415166481":{"events":{"click":[...

Obviously calling parse on this string will not produce a true JQuery object reference. I’m curious if you can use this string identifier to obtain a reference to the original object, assuming the original object as still allocated? What do these jQuery360064998935415166481 style identifiers represent?

I’m working with WASM where passing object references has limitations and requires unique approaches to fake preserve/restore handles to objects, and am wondering if these identifiers would be useful in my toolkit of approaches of overcoming these limitations. I’d appreciate it greatly if we can avoid devolving into a discussion about the premise of the question.

2

Answers


  1. Chosen as BEST ANSWER

    I'm not marking this as answer because I don't know that it's completely reliable or why it over-fetches in some cases. It at least shows that it is possible to take the string expando ID and locate the object, and could probably be refined into something reliable:

    https://jsfiddle.net/3hwvor46/

    $('#btn1').on("click", function(e){
      console.log("clicked");
      var eventTargetExpandoId = Object.keys(JSON.parse(JSON.stringify(e.target)))[0];
      console.log(eventTargetExpandoId);
      // assume some context switch where we no longer have the e reference 
      // but only have the string eventTargetExpandoId and want to get the object ref back
      var foundWithProperty = $('*').filter(function(){return this[eventTargetExpandoId] !== undefined;});
      console.log("Count Items found", foundWithProperty.length);
      console.log("Items", foundWithProperty);
    });
    

    Console showing located button


    • No. You cannot convert back (parse) a stringified string to its original instance.
    • That string is just the jQuery version with a random number attached. You can find a clue in the jQuery’s core.js file
      jQuery.extend( {
      
          // Unique for each copy of jQuery on the page
          expando: "jQuery" + ( version + Math.random() ).replace( /D/g, "" ),
      

    Basically:

    console.log(`jQuery${ ("3.6.0" + Math.random()).replace(/D/g, "") }`);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search