0

Possible Duplicate:
How to catch exceptions in javascript?

I am changing old web application. Unfortunately to some of layout changes is generated components I didn't find any reasonable solution, so I was forced to use 'javascript hacks'. My template on the end of loading page load javascript file 'layoutfixes.js' that change some generated components. Generated commponents have various Ids or do not ha them at all, so sometime I had to obtain element in terrible way, like this:

var tdNodes = document.getElementById('tabbedPanel').childNodes[1].childNodes[0]. ... .childNodes[0];

But as I said not every page has those components, so lines as above throw error that element is null. I do not what add everywhere checking if there exist such element on page or not. I whould perfer add something like "try{} catch(Exception e){}" in that javascript. But I am not familar with javascript enough. Is in javascript something like that?

Community
  • 1
  • 1
M314
  • 925
  • 3
  • 13
  • 37
  • 2
    Please do a little research on your own. A simple Google search for "JavaScript try catch" will point you in the right direction. – Lukas Jan 10 '13 at 13:19

4 Answers4

1

Hack is the right word for what you are doing there. As you are already well into the world of hackery you might as well add another with a try/catch:

try {
  document.getElementById('tabbedPanel').childNodes[1]
}
catch ( ex ) {
 // do nothing
}

More info here: http://www.w3schools.com/js/js_errors.asp

Pete Duncanson
  • 3,208
  • 2
  • 25
  • 35
1

Javascript does indeed have a try/catch implementation:

try {
    // add code that can throw exceptions
}
catch (e) {
   // statements to handle any exceptions
}
MrCode
  • 63,975
  • 10
  • 90
  • 112
1

Java script does support exception handling. You can code as:

try {
    foo.bar();
} catch (e) {
    alert(e.name + ": " + e.message);
}

you can find more info here: http://www.w3schools.com/js/js_errors.asp

Kai
  • 113
  • 8
1

You can use Try Cache as other answers suggested, but I assume you want to traverse the children of a specific node. In that case, the following code can solve the problem:

var tdNodes = document.getElementById('tabbedPanel');

for ( var i = 0; i < tdNodes.length; i++ ) {
  //do something with childNodes[i]
}

If you want to browse the whole DOM (document object model), you can use a recursive call like this:

var tdNodes = document.getElementById('tabbedPanel');

function doSomethingWithNode( node ) {
  //process the node and do whatever you like

  //process all the children with a recursive call
  for ( var i = 0; i < tdNodes.length; i++ ) {
    doSomethingWithNode( childNodes[i] );
  }  
}
AlexStack
  • 16,766
  • 21
  • 72
  • 104