Results 1 to 3 of 3

Thread: Javascript -- Iterate throught page elements

  1. #1

    Thread Starter
    Frenzied Member
    Join Date
    Aug 2000
    Location
    Birmingham, AL
    Posts
    1,276

    Question Javascript -- Iterate throught page elements

    Is there a way to iterate through page elements in JS so you don't have to use the syntax document.getElementById('ctrlName') ?

  2. #2
    Fanatic Member Psyrus's Avatar
    Join Date
    Jul 2000
    Location
    NJ
    Posts
    602

    Re: Javascript -- Iterate throught page elements

    You could use the DOM and access the individual nodes. Here's a quick sample:
    HTML Code:
    <html>
    <head>
    <title>Testing Node Iteration</title>
    <script type = "text/javascript">
    function showNodes(){
    	var vHtml = document.childNodes[0];
    	var vHead = vHtml.childNodes[0];
    	var vTitle = vHead.childNodes[0];
    	var vScript = vHead.childNodes[1];
    	var vBody = vHtml.childNodes[1];
    	var vLen = vBody.childNodes.length;
    	for(var i = 0; i < vLen - 1; i++){
    		alert(vBody.childNodes[i].tagName);
    	}
    }
    
    </script>
    </head>
    <body onload = "showNodes();">
    <h1>Testing Node Iteration</h1>
    <div ID = "div1">Division One</div>
    <div ID = "div2">Division Two</div>
    <div ID = "div3">Division Three</div>
    </body>
    </html>
    Of course you would want to better optimize the code by using loops to iterate through the nodes, but you get the idea.

    To test for child nodes use hasChildNodes(). You can then get the length using childNodes.length. There are other methods available. You can check out the W3C for more details but here is a start:

    http://www.w3.org/TR/REC-DOM-Level-1...e-binding.html
    Chris

    VB 6.0 Calendar App Video Gamers Group
    Don't forget to rate people if they helped you.

  3. #3
    Kitten CornedBee's Avatar
    Join Date
    Aug 2001
    Location
    In a microchip!
    Posts
    11,594

    Re: Javascript -- Iterate throught page elements

    That code won't work. In all browsers but IE, childNodes will contain text nodes as well.

    document.getElementsByTagName('*') will give you an array of all elements in the page.
    All the buzzt
    CornedBee

    "Writing specifications is like writing a novel. Writing code is like writing poetry."
    - Anonymous, published by Raymond Chen

    Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width