PDA

View Full Version : try - catch and removeChild questions


Graeme Hackston
01-06-2003, 07:01 AM
I have 2 questons regarding the example here:

http://msdn.microsoft.com/workshop/author/dhtml/reference/methods/removechild.asp

This is the code:

<html>
<HEAD>
<SCRIPT>
function removeElement()
{
try
{
//The first child of the div is the bold element.
var oChild=Div1.children(0);
Div1.removeChild(oChild);
}
catch(x)
{
alert("You have already removed the bold element.
Page will be refreshed when you click OK.")
document.location.reload();
}
}
</SCRIPT>
</HEAD>
<BODY>
<DIV ID=Div1 onclick="removeElement()">
Click anywhere in this sentence to remove this <B>Bold</B> word.
</DIV>
</BODY>
</html>


1/ Where does the "x" come from in "catch(x)" ?

2/ When removing the element, how do I make a variable of the division id ?

example:

a = '1'

document.getElementById('Div' + a)

ahosang
01-06-2003, 10:58 AM
function removeElement(a)
{
try
{
//The first child of the div is the bold element.
var theDiv=document.getElementById("Div"+a);
var oChild=theDiv.children(0);
theDiv.removeChild(oChild);
}
catch(x) { //x is just the error object, some people use e - doesn't matter
alert("You have already removed the bold element.
Page will be refreshed when you click OK.")
document.location.reload();
}
}

<DIV ID=Div1 onclick="removeElement(1)">

jkd
01-06-2003, 05:37 PM
You should be using childNodes.item(N) instead of .children(N)

I was looking for a link on the JS1.5 guide to explain explain the Error() contructor for you - but it doesn't cover it! Very surprising.

Anyway, try...catch:
http://devedge.netscape.com/library/manuals/2000/javascript/1.5/reference/stmt.html#1051663

But unbeknownst to many, on top of your typical Number, String, Boolean, etc constructors, there is an Error one.

Alex Vincent could tell you all you wanted to know about it... he even got a stacktrace property added to Mozilla's Error.prototype, which is great for debugging. :)

Graeme Hackston
01-06-2003, 11:20 PM
Thanks guys, that makes sense.