removeChild doesn't remove in IE

In one of the pages in my application, I need to create several table rows using JavaScript and provide users the ability to remove certain rows. I am using removeChild to remove the rows from the table. This works in Firefox and Opera but not IE. What can I do to make it work in IE?

I have reproduced a simple JavaScript block that behaves the same way. Any help will be appreciated.

<html>
<head><title></title></head>
<body>

<div id="block"></div>

<script type="text/javascript">

function Initialize()
{
	var element = document.getElementById('block');

	for (i = 1; i < 6; i++)
	{
		var e = document.createElement('div');
		e.setAttribute('id', 'element' + i);
		e.innerHTML = 'Option ' + i;

		var l = document.createElement('a');
		l.setAttribute('href', '#');
		l.setAttribute('onclick', 'RemoveMe(' + i + ');');
		l.innerHTML = ' remove';
		
		e.appendChild(l);
		element.appendChild(e);
	}
}

function RemoveMe(id)
{
	var elementid = 'element' + id;
	var element = document.getElementById(elementid);
	element.parentNode.removeChild(element);
}

Initialize();
</script>

</body>
</html>

Don’t use setAttribute to attach an event listener. Do it like this:


[...]
l.onclick = function () { RemoveMe (i); };

Remember to return false in your RemoveMe function.

That won’t work, since the value of i will always be 6.

Instead, you can find the target element from the Event object that is passed to the event handler (using the .target property in Opera/Firefox/Safari or the .srcElement property in IE).

I don’t know if it a lot to ask, but can you give me a code example? Thanks.

<!DOCTYPE type PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <title>Remove Child</title>
    <script type="text/javascript">
      function Initialize() {
          var element = document.getElementById('block');

          for (var i = 1; i < 6; ++i) {
              var e = element.appendChild(document.createElement('div'));
              e.setAttribute('id', 'element' + i);
              e.appendChild(document.createTextNode("Option " + i));

              var l = e.appendChild(document.createElement('a'));
              l.setAttribute('href', '#');
              l.appendChild(document.createTextNode(" remove"));
              l.onclick = RemoveMe;
          }
      }

      function RemoveMe(e) {
          e = e || window.event;
          var element = e.target ? e.target : e.srcElement;
          element.parentNode.parentNode.removeChild(element.parentNode);
          if (e.preventDefault) {
              e.preventDefault();
              e.stopPropagation();
          } else {
              e.returnValue = false;
              e.cancelBubble = true;
          }
      }
    </script>
  </head>
  <body>
    <div id="block"></div>

    <script type="text/javascript">
      Initialize();
    </script>
</body>
</html>

Tested in Opera 9.2, Firefox 2.0 and IE 6.

Thanks a lot. I appreciate it.