Recursive node traversal locks browser

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Ryan Stewart

    #1

    Recursive node traversal locks browser

    Putting the following code in a page seems to make it go into an infinite
    loop unless you give it a very simple node to work with. Either that or it's
    very very slow. I'm somewhat new to this, having limited experience with
    hacking out JavaScript but no serious coding with it. I do have programming
    experience though. The logic seems fine to me. Is there something I'm
    missing?

    <script type="text/javascript">
    var out = "";

    function listNodes(node) {
    out += node + "\n";
    for (i = 0; i < node.childNodes .length; i++) {
    listNodes(node. childNodes[i]);
    }
    }

    listNodes(docum ent.getElementB yId("listMe"));
    alert(out);
    </script>



  • RobG

    #2
    Re: Recursive node traversal locks browser

    Ryan Stewart wrote:
    [color=blue]
    > experience though. The logic seems fine to me. Is there something I'm
    > missing?
    >
    > <script type="text/javascript">
    > var out = "";[/color]

    Does out need to be global? If not, put it inside the
    function and keep it local
    [color=blue]
    > function listNodes(node) {
    > out += node + "\n";[/color]

    This concatenates the value of "node" on the end of "out"
    and appends a new line. If node is a HTML element, IE will
    report it as [ojbect], other browsers may include more
    information.
    [color=blue]
    > for (i = 0; i < node.childNodes .length; i++) {
    > listNodes(node. childNodes[i]);[/color]

    Here you call the function "listNodes" but do not
    define it (I think you tried but forgot the keyword
    "function ",
    [color=blue]
    > listNodes(docum ent.getElementB yId("listMe"));
    > alert(out);[/color]

    You mean: function listNodes()...


    It would help if you included a minimal implementation of
    "node". The code below should do what you want.

    There is no need for a function "listNodes"
    since you are remembering them all in the variable "out".
    You can call the alert directly from the onclick - this
    makes the function more generic, all it will do is return
    the list so you can do what you want with it (in this case,
    display it).

    <script type="text/javascript">
    function listNodes(aNode ) {
    var out = '';
    if(aNode.childN odes) {
    for (var i = 0; i < aNode.childNode s.length; ++i) {
    out += '\nNode ' + i + ': '
    + aNode.childNode s[i].nodeName;
    }
    }
    return(out);
    }
    </script>

    <table border="1" id="listMe">
    <tr>
    <td><form name="aForm" action="">
    <input type="button" value="Table kids" onclick="
    alert(listNodes (document.getEl ementById('list Me')));
    "><br>
    <input type="button" value="Form kids" onclick="
    alert(listNodes (this.form));
    ">
    <p>a cell</p></td><td>a cell</td><td>a cell</td>
    </tr><tr>
    <td>a cell</td><td>a cell</td><td>a cell</td>
    </tr><tr>
    <td>a cell</td><td>a cell</td><td>a cell</td>
    </tr>
    </table>


    Comment

    • RobG

      #3
      Re: Recursive node traversal locks browser

      RobG wrote:

      [snip][color=blue]
      > <table border="1" id="listMe">
      > <tr>
      > <td><form name="aForm" action="">
      > <input type="button" value="Table kids" onclick="
      > alert(listNodes (document.getEl ementById('list Me')));
      > "><br>
      > <input type="button" value="Form kids" onclick="
      > alert(listNodes (this.form));
      > ">
      > <p>a cell</p></td><td>a cell</td><td>a cell</td>
      > </tr><tr>
      > <td>a cell</td><td>a cell</td><td>a cell</td>
      > </tr><tr>
      > <td>a cell</td><td>a cell</td><td>a cell</td>
      > </tr>
      > </table>[/color]

      Dang!! Forgot to close the <form>... Replace the table with
      the following:

      <table border="1" id="listMe">
      <tr>
      <td><form name="aForm" action="">
      <input type="button" value="Table kids" onclick="
      alert(listNodes (document.getEl ementById('list Me')));
      "><br>
      <input type="button" value="Form kids" onclick="
      alert(listNodes (this.form));
      ">
      <p>a cell</p>
      </form>
      </td><td>a cell</td><td>a cell</td>
      </tr><tr>
      <td>a cell</td><td>a cell</td><td>a cell</td>
      </tr><tr>
      <td>a cell</td><td>a cell</td><td>a cell</td>
      </tr>
      </table>

      Cheers, Rob.

      Comment

      • Ryan Stewart

        #4
        Re: Recursive node traversal locks browser

        "RobG" <rgqld@iinet.ne t.auau> wrote in message
        news:Vd07d.1535 $aA.54355@news. optus.net.au...[color=blue]
        > Ryan Stewart wrote:[color=green]
        > > experience though. The logic seems fine to me. Is there something I'm
        > > missing?
        > >
        > > <script type="text/javascript">
        > > var out = "";[/color]
        >
        > Does out need to be global? If not, put it inside the
        > function and keep it local
        >[/color]
        I'm fairly certain it needs to be global, though again I'm not intimately
        familiar with the way JS handles variables. Besides which, keeping it global
        simplifies things greatly.
        [color=blue][color=green]
        > > function listNodes(node) {
        > > out += node + "\n";[/color]
        >
        > This concatenates the value of "node" on the end of "out"
        > and appends a new line. If node is a HTML element, IE will
        > report it as [ojbect], other browsers may include more
        > information.
        >[/color]
        I'm aware of this. FireFox includes more information in the form of what
        type of object it is.
        [color=blue][color=green]
        > > for (i = 0; i < node.childNodes .length; i++) {
        > > listNodes(node. childNodes[i]);[/color]
        >
        > Here you call the function "listNodes" but do not
        > define it (I think you tried but forgot the keyword
        > "function ",
        >[/color]
        Yes I do. It's the function that includes this code.
        [color=blue][color=green]
        > > listNodes(docum ent.getElementB yId("listMe"));
        > > alert(out);[/color]
        >
        > You mean: function listNodes()...
        >[/color]
        No, I mean a recursive function call.
        [color=blue]
        > It would help if you included a minimal implementation of
        > "node". The code below should do what you want.
        >[/color]
        A minimal implementation of node? Not following you. And the code doesn't do
        what I need. Take another look at my code as I've described it. It's
        intended to take any node and traverse all children to the bottom (or top,
        depending on your perspective) of the tree. In your implementation, calling
        the function for the table only gives one thing: tbody. I need it to list
        tbody, the three tr's inside it, and each of the td's inside of them. This
        isn't actually about listing the nodes. It's about traversing the tree to
        find nodes with particular characteristics , like a particular class
        attribute. I see being able to list all of them as the first step toward
        this goal.
        [color=blue]
        > There is no need for a function "listNodes"
        > since you are remembering them all in the variable "out".
        > You can call the alert directly from the onclick - this
        > makes the function more generic, all it will do is return
        > the list so you can do what you want with it (in this case,
        > display it).
        >[/color]
        *snip code*


        Comment

        • Agent Smith

          #5
          Re: Recursive node traversal locks browser

          >[color=blue]
          > function listNodes(node) {
          > out += node + "\n";
          > for (i = 0; i < node.childNodes .length; i++) {
          > listNodes(node. childNodes[i]);
          > }
          > }
          >[/color]


          Hey I think the problem is that you are not declaring a new variable i for
          each recursive trip. There for as soon as you pass in a node with a child
          node i is constantly reset to 0. Your for loop should look like this:

          function listNodes(node) {
          out += node + "\n";
          for ( var i = 0; i < node.childNodes .length; i++) {
          listNodes(node. childNodes[i]);
          }
          }

          Now everytime the method is called a new instance of the variable i is
          created and it's state is maintained. Another way of putting it is the
          variable i in your existing for loop is a global variable, so its value is
          common to all recursive calls.

          -Smith


          Comment

          • RobG

            #6
            Re: Recursive node traversal locks browser

            Ryan Stewart wrote:

            [snip][color=blue]
            > I'm fairly certain it needs to be global, though again I'm not intimately
            > familiar with the way JS handles variables. Besides which, keeping it global
            > simplifies things greatly.[/color]

            Up to you :-)

            [snip][color=blue]
            > I'm aware of this. FireFox includes more information in the form of what
            > type of object it is.[/color]
            Yes, but it lulls you into a false sense of security.
            nodeName will return the proper HTML name of the node.

            [snip][color=blue][color=green]
            >> Here you call the function "listNodes" but do not
            >> define it (I think you tried but forgot the keyword
            >> "function ",[/color][/color]
            [snip][color=blue]
            > Yes I do. It's the function that includes this code.[/color]
            [snip]

            Quite right, sorry, a bit brain dead today. You are
            recursively calling the function, which can be deadly if
            you have no way of escaping.

            [snip][color=blue]
            > No, I mean a recursive function call.[/color]
            [snip]
            Yeah, I missed it but it's better to avoid recursion if you
            can for the above reason - it can be very hard to debug
            when your browser keeps locking up in enless loops because
            of bugs in code.
            [color=blue]
            > A minimal implementation of node? Not following you.[/color]
            [snip]

            A minimal bit of HTML and what you expect your function to
            return. Your "function listNodes(node) " expects to be
            given an argument to be put into the variable "node", but
            you don't tell us what you are putting in there - I just
            guessed that you are putting in a reference to a node (e.g.
            this.form).
            [color=blue]
            > And the code doesn't do
            > what I need. Take another look at my code as I've described it. It's
            > intended to take any node and traverse all children to the bottom (or top,[/color]
            [snip]

            Ah, but that that's not what childNodes gives you -
            childNodes returns the direct children of the current node
            (your "node"), not their children. That is, the firstChild
            plus its siblings. Otherwise, body.childNodes would return
            every single node in the document - it doesn't. In the
            example I gave, body has a script and a table child
            (Firefox adds in some extra text nodes too but IE doesn't)
            and that's it. Firefox says 5 kids (there's an extra text
            node after body, script and table), IE says 2 (script &
            table).

            If you'd given some code and what you wanted....
            [color=blue]
            > depending on your perspective) of the tree. In your implementation, calling
            > the function for the table only gives one thing: tbody.[/color]
            [snip]

            because that is the only child of TABLE. The children of
            TBODY are the TRs. The Children of the TRs are the TDs,
            etc.


            I need it to list[color=blue]
            > tbody, the three tr's inside it, and each of the td's inside of them. This
            > isn't actually about listing the nodes. It's about traversing the tree to
            > find nodes with particular characteristics , like a particular class
            > attribute. I see being able to list all of them as the first step toward
            > this goal.[/color]
            [snip]

            There is no single function (AFAIK) that lists every single
            node below the current one.

            I have a script to do it, the algorithm is to find the
            first child, then keep going down first kids till you hit
            the end of the branch. Now go to nextSibling and try going
            down further. Each time you hit the end, you look for more
            siblings and children. When you can't go any deeper, you
            start coming back up, all the time trying to traverse more
            siblings and decend deeper into the tree. Eventually you
            end up at the point you started (or the top of the document
            if you miss your start...).

            Code follows ... it was an early script, so not very good
            but shows how to do it. Put the script into a .js file,
            then call it from wherever.

            *Check for wrapping*. I have tried to make sure it's OK
            but may have missed some.



            /* DOM Walk
            * Author: RobG
            * Date: September, 2004
            * Description: Reports on nodes
            * Call:
            displayReport(< window_name>,re portDOM(<doc_re ference>));">
            * e.g. displayReport(' A
            Report',reportD OM(document.get ElementById('aD iv'));
            */

            // adds 1 to last number of index
            // e.g. 1,1,2 becomes 1,1,3
            function indexAdd(indexV al) {
            var a = indexVal.split( ',');
            var c = '';
            for (var i=0; i<a.length; ++i) {
            var b = parseInt(a[i]);
            if ( i == (a.length - 1)) {++b}
            if ( c == '') {c = String(b);
            } else {c += ',' + String(b);
            } }
            return c;
            }

            // indexTrim
            // trims last value from index
            // e.g. 1,0,1 becomes 1,0
            function indexTrim(index Val) {
            var x = indexVal.split( ',');
            var z = x[0];
            for (var i=1; i<x.length - 1; ++i){
            z += ',' + x[i];
            } return z;
            }

            // Navigates a DOM
            // Walks down firstChild until the end, then
            // retreats to the first nextSibling up the
            // tree until it gets back to the start and
            // there are not more nextSiblings
            function reportDOM(start Point) {
            var idx = '0';
            var keepGoing = 'yes';
            var msg = '';

            if (arguments.leng th == 0) startPoint = window.document ;
            if (startPoint) {
            var thePoint = startPoint;
            var count = 0;
            msg = printDetail(cou nt,idx,thePoint ,msg);
            } else {
            alert('startPoi nt not valid');
            keepGoing = 'no';
            }

            // Keep doing this till I say stop...
            while (keepGoing == 'yes') {
            // if there are kids
            if (thePoint.first Child) {
            thePoint = thePoint.firstC hild;
            idx += ',' + 0;
            ++count;
            msg = printDetail(cou nt,idx,thePoint ,msg);

            // Not gone into kid loop, if sibs, do instead
            } else if (thePoint.nextS ibling) {
            thePoint = thePoint.nextSi bling;
            idx = indexAdd(idx);
            ++count;
            msg = printDetail(cou nt,idx,thePoint ,msg);

            } else {

            // If no kids or sibs, retreat up the tree until find
            // a nextSibling. If get to the top without findng one,
            // or if keepGoing has been set to no, we've finished
            while (!thePoint.next Sibling && keepGoing == 'yes') {
            thePoint = thePoint.parent Node;
            idx = indexTrim(idx);

            // If going up put us back to the top, that's it.
            if (idx == '0') keepGoing = 'no';
            }

            // Have to test here as 'while' not evaluated yet - if
            // thePoint.nextSi bling undefined ('cos we're at top)
            // script will crash
            if (keepGoing == 'yes') {
            thePoint = thePoint.nextSi bling;
            idx = indexAdd(idx);
            ++count;
            msg = printDetail(cou nt,idx,thePoint ,msg);
            } } }
            return msg;
            }

            // printDetail
            // Writes details of the point passed to it
            // as HTML. Expects output to be put in a table
            function printDetail(c,x ,p,m){
            m += '<tr><td class=\"count\" >' + c + '</td>'
            + '<td class=\"idx\">' + x + '</td>'
            + '<td><span class=\"kind\"> ' + p.nodeName
            if (p.type) {m += ' ' + p.type}
            m += '</span></td>'
            + '<td><span class=\"name\"> ';
            if (p.name) {m += p.name;}
            if (p.id && p.name) {m += '/' + p.id;}
            if (p.id && !p.name) {m += p.id;}
            // else {m += '&nbsp;'}
            m += '</span></td>'
            + '<td align=\"center\ "><span class=\"type\"> ' +
            p.nodeType + '</span></td>'
            + '<td align=\"center\ "><span class=\"kids\"> ' +
            p.childNodes.le ngth + '</span></td></tr>';
            return m;
            }

            // displayReport
            // Opens a new window and writes the data to it
            // thingName is a name of the thing being reported on
            // content is the stuff to write
            function displayReport(t hingName,conten t) {
            repWindow =
            window.open('', 'result','width =550,height=700 ,menubar=0'
            + ',toolbar=1'
            + ',status=0'
            + ',scrollbars=1'
            + ',resizable=1') ;
            // Styles are here, but could use external sheet
            repWindow.docum ent.writeln(
            '<html><head><t itle>Report for: '
            + thingName
            + '</title>'
            + '<style type=\"text/css\">'
            + '.plain, .count, .idx, .kind, .name, .type, .kids, .legend'
            + '{font-weight: normal; font-family: sans-serif; '
            + ' font-size: 12px; color: \#333333;} '
            + 'th'
            + '{border-bottom: 1px solid \#999999;}'
            + 'td'
            + '{border-bottom: 1px solid \#999999;}'
            + '.count'
            + '{padding-right: 15; text-align: right;}'
            + '.idx'
            + '{padding-right: 10;}'
            + '.name'
            + '{padding-left: 5;}'
            + '</style>'
            + '</head><body onLoad=\"self.f ocus()\">'
            + '<table border=\"0\" cellpadding=\"2 \"
            cellspacing=\"0 \" width=\"100\%\" >'
            + '<tr><td style=\"border-bottom: none;\">'
            + '<h2><span class=\"plain\" >DOM Walk Report on:</span> '
            + thingName
            + '</h2>'
            + '</td><td style=\"padding : 0 20 0 0; text-align: right;
            border-bottom: none;\">'
            + '<a href=\"#NTlegen d\">Node Type Legend</a>&nbsp;|&nbsp; '
            + '<a href=\"javascri pt:window.close ();\">Close</a></td>'
            + '</tr></table>'
            + '<table border=\"0\" cellpadding=\"2 \" cellspacing=\"0 \">'
            + '<tr><th>\#</th>'
            + '<th align=\"left\"> Index</th>'
            + '<th align=\"left\"> Kind</th>'
            + '<th align=\"left\"> Name/id</th>'
            + '<th align=\"center\ ">Node Type</th>'
            + '<th align=\"center\ ">\# Kids</th></tr>'
            + content
            + '</table><br>'
            + '<table border=\"0\" cellpadding=\"2 \" cellspacing=\"0 \">'
            + '<tr><th colspan=\"2" align=\"left\"> '
            + '<a name=\"NTlegend \">Node Type Legend</a></th></tr>'
            + '<tr><td class="count">1 </td><td
            class="legend"> ELEMENT_NODE</td></tr>'
            + '<tr><td class="count">2 </td><td
            class="legend"> ATTRIBUTE_NODE</td></tr>'
            + '<tr><td class="count">3 </td><td
            class="legend"> TEXT_NODE</td></tr>'
            + '<tr><td class="count">4 </td><td
            class="legend"> CDATA_SECTION_N ODE</td></tr>'
            + '<tr><td class="count">5 </td><td
            class="legend"> ENTITY_REFERENC E_NODE</td></tr>'
            + '<tr><td class="count">6 </td><td
            class="legend"> ENTITY_NODE</td></tr>'
            + '<tr><td class="count">7 </td><td
            class="legend"> PROCESSING_INST RUCTION_NODE</td></tr>'
            + '<tr><td class="count">8 </td><td
            class="legend"> COMMENT_NODE</td></tr>'
            + '<tr><td class="count">9 </td><td
            class="legend"> DOCUMENT_NODE</td></tr>'
            + '<tr><td class="count">1 0</td><td
            class="legend"> DOCUMENT_TYPE_N ODE</td></tr>'
            + '<tr><td class="count">1 1</td><td
            class="legend"> DOCUMENT_FRAGME NT_NODE</td></tr>'
            + '<tr><td class="count">1 2</td><td
            class="legend"> NOTATION_NODE</td></tr>'
            + '</table><br>'
            + '<div style=\"padding : 0 20 0 0; text-align: right;\">'
            + '<a href=\"\"
            onclick=\"javas cript:window.cl ose();\">Close</a></div>'
            + '</body></html>'
            );
            repWindow.docum ent.close();
            }

            Comment

            • RobG

              #7
              Re: Recursive node traversal locks browser

              Agent Smith wrote:

              [color=blue]
              > Hey I think the problem is that you are not declaring a new variable i for
              > each recursive trip. There for as soon as you pass in a node with a child
              > node i is constantly reset to 0. Your for loop should look like this:[/color]

              You are perfectly correct... what was I thinking?

              Comment

              • Richard Cornford

                #8
                Re: Recursive node traversal locks browser

                RobG wrote:
                <snip>[color=blue]
                > Quite right, sorry, a bit brain dead today. You are
                > recursively calling the function, which can be deadly if
                > you have no way of escaping.[/color]
                <snip>

                Recursing through the childNodes of a DOM tree should be finite because
                all the branches should eventually come to an end. However, invalid
                mark-up can result in DOM structures that are not that tree-like, and
                may even have child references that point to ancestors, which would
                recurse for ever (though you really have to screw the HTML up to achieve
                that).

                Richard.


                Comment

                • Ryan Stewart

                  #9
                  Re: Recursive node traversal locks browser

                  "Agent Smith" <john64205@hotm ail.com> wrote in message
                  news:45GdnTu3Hd xdL8HcRVn-vQ@comcast.com. ..[color=blue][color=green]
                  > > for (i = 0; i < node.childNodes .length; i++) {[/color]
                  >
                  > Hey I think the problem is that you are not declaring a new variable i for
                  > each recursive trip. There for as soon as you pass in a node with a child
                  > node i is constantly reset to 0. Your for loop should look like this:
                  >[/color]
                  Perfect. That's exactly what my problem was. Thanks very much. In
                  retrospect, it makes perfect sense.


                  Comment

                  Working...