How get jQuery data without jQuery

Sometimes there is a need to get access to data value when jQuery is not available, this may happen when the website is using jQuery.noConflict(true) and don’t give access to jQuery it uses. Adding your own jQuery don’t work because data (added by calling .data('name', value) not by data-name attribute) is accessible only from same jQuery in which data was added.

But there is solution for this. First we need helper function (if we don’t want to include another jQuery):

var $$ = function(selector) {
  return [].slice.call(document.querySelectorAll(selector));
};

Looking at the source code for jQuery you will see this code:

function Data() {
    this.expando = jQuery.expando + Data.uid++;
}

Data.uid = 1;

Data.prototype = {

    cache: function( owner ) {

        // Check if the owner object already has a cache
        var value = owner[ this.expando ];
        ...

and each jQuery have it’s own jQuery.expando which is string jQuery + version + random number.

So we need to extract expando values from DOM node, here is the code:

function expando(item) {
    return Object.keys(item).filter(function(key) {
        return key.match(/^jQuery/);
    }).map(function(key) {
        return item[key];
    });
}

in most cases there are two expando attributes not only for data but also for events. Next step is to find data value:

function data(item, name) {
    return expando(item).map(function get(expando) {
        return expando[name];
    }).filter(Boolean);
}

You can test this approach in this pen, the terminal is created inside IIFE and jQuery.noConflict(true) is called, (in Google Chrome you need to select from dropdown result(gGwROe) frame to interact with the page).

You can test by calling inject_jquery() function (that’s defined in pen) that $('.terminal').data('terminal') don’t work (you either can’t call $('.terminal').terminal() unless you include jQuery Terminal again.

But if you copy/paste $$, expando and data functions into console and call:

var term = data($$('.terminal')[0], 'terminal')[0];

you will have access to terminal instance, you can call term.clear() to clear the terminal or any other terminal method.

Advertisements

,

  1. How get jQuery data without jQuery – PipisCrew Official Homepage

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: