Ken wrote:
Over the various browsers, is it better to use:
document.getElementById('num1').removeChild(image_ display);
or
image_display.parentNode.removeChild(image_display );
to remove an image.
Ken
Don't use round brackets to address array elements (it is an IE-ism):
document.getElementById['num1'].removeChild(image_display);
Regarding how to reference the thing you want to delete, it depends on
what you are doing. If the thing you want to delete can be found using
a widely supported and simple DOM method (maybe it's a named node in a
form), then pass a direct reference to it:
<form...>
....
<input type="button" value="Delete something"
onclick="deleteIt(this.form.aNode);">
</form>.
and the function can be really simple:
function deleteIt(x) {
x.parentNode.remvoeChild.x;
}
However, sometimes the document tree will not provide a simple solution
or there is no reliable relationship between the element being clicked
and the one that is to be deleted. In this case, you can pass a string
id and use getElementById(). If the image does not have an id, then
you can trawl through the collection given by
getElementsByTagName('img'), but it is somewhat more long winded.
If using either of the getElement(s) methods, you need to do feature
testing to ensure the users' browser supports it. Rather than put the
feature test code into the thing that is running the function (say a
link or button), you need to include it in the delete function -
otherwise you will be replicating feature test code on every element
that has an action.
Having passed the id of some element that you know you can use to
establish a relationship with the element to be deleted, use
getElementById(), then parentNode :
function deleteIt(theThing) {
if (document.getElementById) {
var a = document.getElementById(theThing);
a.parentNode.remvoeChild(a);
} else {
// some alternative if getElementById not supported
}
}
The parentNode is good because it guarantees the relationship. Also,
by removing any hard coded references from the function, you can use it
to delete lots of things, not just images. Note that you could replace
"a" above with document.getElement....theThing); in each instance, but
it seems neater to use a variable.
Hope that helps! Rob