Clear all script-set variables easily (Javascript/jQuery)

15,380

Assuming that you're attaching variables to DOM elements as properties (which you should be careful not to create a cyclic reference and trigger IE memory leaks; see: crockford article).

In the article about leaks, Mr. Crockford gives a function for purging function references from all DOM elements, which is similar to what you need:

function purge(d) {
    var a = d.attributes, i, l, n;
    if (a) {
        l = a.length;
        for (i = 0; i < l; i += 1) {
            n = a[i].name;
            if (typeof d[n] === 'function') {
                d[n] = null;
            }
        }
    }
    a = d.childNodes;
    if (a) {
        l = a.length;
        for (i = 0; i < l; i += 1) {
            purge(d.childNodes[i]);
        }
    }
}

Where he has

if (typeof d[n] === 'function') {

Replace with logic that checks for your custom attributes/properties (keep a list handy in an array if you use a lot of different ones, and make sure that none of your property names conflict with standard attributes like src, title, etc.)

Share:
15,380
Mark
Author by

Mark

Updated on June 20, 2022

Comments

  • Mark
    Mark almost 2 years

    I'm trying to find a simple way to reset all current variables in the DOM. My app has a 'locked' state, but currently, when locked, the last set of information is still visible in the DOM if you look using Firebug for example.

    I know all the names of all variables, but I don't want to have a really cumbersome script including all of them (there are approx. 300) where I explicitly clear their values.

    Does anybody know if there's a way to 'purge' the DOM of all set vars?

    Apologies in advance if this is a silly question, and thanks for any responses. My app uses jQuery extensively, but all my Javascript/jQuery searches have come up blank.