views:

76

answers:

4

When removing an element with standard JavaScript, you must go to it's parent first:

element = document.getElementById("element-id");
element.parentNode.removeChild(element);

Having to go to the parent node first seems a bit odd to me, is there a reason JavaScript works like this?

A: 

From what I understand, removing a node directly does not work in Firefox, only Internet Explorer. So, to support Firefox, you have to go up to the parent to remove it's child.

Ref: http://chiragrdarji.wordpress.com/2007/03/16/removedelete-element-from-page-using-javascript-working-in-firefoxieopera/

James
That doesn't really answer my question, and the page you linked to provides a worse solution than mine.
Josh
A: 

You may want to try the following code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  </head>
  <body>
    <div>
      <p id="one">The 1st line.</p>
      <p id="two">The 2nd line.</p>
      <p id="three">The 3rd line.</p>
      <button>Remove the 3rd line.</button>
    </div>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"&gt;&lt;/script&gt;
    <script type="text/javascript">
      $(function(){
        $("button").click(function () {
          $("#three").remove();
        });
      });
    </script>
  </body>
</html>

Please refer to http://api.jquery.com/remove/ for details.

boxoft
Strange. Isn't jQuery a JavaScript framework?
boxoft
+3  A: 

It's what the DOM supports. Search that page for "remove" or "delete" and removeChild is the only one that removes a node.

That answers my original question, but why does JavaScript work like this?
Josh
+1  A: 

You could make a function that did the removing for you so that you wouldn't have to think about it every time.

function remove(id)
{
    return (elem=document.getElementById(id)).parentNode.removeChild(elem);
}
xsznix
I'm not going to be doing any mass deleting of objects so I don't think a function is really worth it.
Josh