|
-
Mar 2nd, 2005, 10:17 AM
#1
Thread Starter
Frenzied Member
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') ?
-
Mar 3rd, 2005, 07:40 AM
#2
Fanatic Member
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
-
Mar 3rd, 2005, 01:52 PM
#3
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|