Is there a way to iterate through page elements in JS so you don't have to use the syntax document.getElementById('ctrlName') ?
Printable View
Is there a way to iterate through page elements in JS so you don't have to use the syntax document.getElementById('ctrlName') ?
You could use the DOM and access the individual nodes. Here's a quick sample:
Of course you would want to better optimize the code by using loops to iterate through the nodes, but you get the idea.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>
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
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.