Recursively reverse all nodes beneath Node n, and reverse Text nodes : Document « Development « JavaScript DHTML






Recursively reverse all nodes beneath Node n, and reverse Text nodes


/*
Examples From
JavaScript: The Definitive Guide, Fourth Edition

Legal matters: these files were created by David Flanagan, and are
Copyright (c) 2001 by David Flanagan.  You may use, study, modify, and
distribute them for any purpose.  Please note that these examples are
provided "as-is" and come with no warranty of any kind.

David Flanagan
*/

// Recursively reverse all nodes beneath Node n, and reverse Text nodes
function reverse(n) { 
    if (n.nodeType == 3 /*Node.TEXT_NODE*/) { // Reverse Text nodes
        var text = n.data;                        // Get content of node
        var reversed = "";
        for(var i = text.length-1; i >= 0; i--)   // Reverse it
            reversed += text.charAt(i);
        n.data = reversed;                        // Store reversed text
    }
    else { // For non-Text nodes recursively reverse the order of the children
        var kids = n.childNodes;
        var numkids = kids.length;
        for(var i = numkids-1; i >= 0; i--) {       // Loop through kids
            reverse(kids[i]);                       // Recurse to reverse kid
            n.appendChild(n.removeChild(kids[i]));  // Move kid to new position
        }
    }
}

           
       








Related examples in the same category

1.Output HTML in JavaScript
2.Output
with Javascript
3.Display info in a new page
4.Reverse the order of the children of Node (document)
5.Open a new document and add some text
6.Get element by name: getElementsByName()
7.Get a specified element using getElementById()
8.Title of a document
9.Referrer of a document (URL of the document)
10.Hide Email Address
11.Convert space to URL encode
12.document last Modified Property in Another Format
13.Checking document referrer
14.Make button (control) visible or invisible
15.Opening a New URL
16. HTML Page with Immediate Script Statements
17.Using document.write() on the Current Window
18.Using document.write() on Another Window
19.Methods and Properties of the Document Object