Click to See Complete Forum and Search --> : [RESOLVED] Try catch for checking element


code?
August 9th, 2008, 02:37 AM
Okay, so here's the deal. I have a function that runs through a for loop, and picks elements and adds them to an array. I don't want to add an element that's not there, so I want to set up a try catch so that it can catch an error and hopefully return when it's trying to get an id that's not there.

How do I check if the generated element id is valid?
Or is there someway I can get the last child in a node, regardless of id?


<div id="mainDiv">
<div id="subDiv1"></div>
<div id="subDiv2"></div>
<div id="subDiv3"></div>
<div id="subDiv4"></div>
<div id="subDiv5"></div>
</div>


Here is some sample code.


function getElements()
{
var elemArray = new array();
for (var i = 1; i < 9; i++)
{
var elem = document.getElementById("subDiv" + i);
elemArray[i - 1] = elem;
}
}

javajawa
August 9th, 2008, 02:43 AM
Here's the easiest way:
if (elem = document.getElementById("subDiv" + i) {

Please note that it uses =, not ==

code?
August 9th, 2008, 02:45 AM
Alright, I'll try that real quick.