views:

42

answers:

2

Here's my stripped down function for recursing through a browsers dom structure.

(function () {
    function displaydom (child, parent) {
        if (parent) {parent = parent+".";}; // if there is no parent then child is the parent

        var jsns = eval(parent+child); // Join parent + child and eval

        for (var i in jsns){ // loop through dom object's attributes
            if (typeof jsns[i] == "object") { // if attribute is an object then recurse through
                // display output here
                displaydom (String(i) /** next child **/, parent+child);
            };
        };
    };
    displaydom ('self', '');
})();

There are a couple - probably simple - problems with it that I haven't been able to get to work (in Chrome):

  1. need to remove eval()
  2. I want to change the for loop to for (var i=0, len = jsns.length; i < len; i++) {}; because it's faster but I keep getting length for jsns '0' or 'undefined'.

P.S - Don't try and run the code as is unless you want your browser to crash!

+1  A: 

Use square bracket notation

        var jsns = parent[obj]

As for your second question…

1. `parent` is an empty string. 2. Strings don't have a `self` property 3. Therefore `"".self` is `undefined` 4. `undefined` has no properties, so it can't have a length property

… you can't use a tranditional for loop over something which isn't an Array (or an array-like object), and most objects are not.

David Dorward
self = window (i.e. I'm iterating through the dom structure). I use self because this sits in an iframe. Also the top 'if' statement compensates for the first empty parent.
EddyR
A: 

To remove eval, you can use square brackets as David said,

var jsns = parent;
if(parent) { 
    jsns = parent[child]; 
}

You can't change the loop, this is because you can't iterate over an object's properties in the way you propose. Object properties can only be accessed by name, they aren't indexed numerically. The only way to do this is the for-in loop you're currently using.

Jani Hartikainen
Ok, I understand - then I guess the problem then is that parent from parent+child in the recursive call is a string - how do I convert a string to a object reference?
EddyR