Get all the objects (DOM or otherwise) using JavaScript

后端 未结 1 1902
无人共我
无人共我 2020-12-19 06:39

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 obj
相关标签:
1条回答
  • 2020-12-19 07:25

    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
    
    0 讨论(0)
提交回复
热议问题