Skip to content Skip to sidebar Skip to footer

Get All The Objects (DOM Or Otherwise) Using JavaScript

The short version: How can I get a list of all the objects (including their descendant objects) on the page (not just the first-depth objects)? Anticipated subproblem: Ho

Solution 1:

My quick attempt:

var objs = []; // we'll store the object references in this array

function walkTheObject( obj ) {
    var keys = Object.keys( obj ); // get all own property names of the object

    keys.forEach( function ( key ) {
        var value = obj[ key ]; // get property value

        // if the property value is an object...
        if ( value && typeof value === 'object' ) { 

            // if we don't have this reference...
            if ( objs.indexOf( value ) < 0 ) {
                objs.push( value ); // store the reference
                walkTheObject( value ); // traverse all its own properties
            } 

        }
    });
}

walkTheObject( this ); // start with the global object

Post a Comment for "Get All The Objects (DOM Or Otherwise) Using JavaScript"