Lenka
Lenka

Reputation: 105

document.RemoveChild not working in JavaScript

in book 'Programming in HTML5 with JavaScript and CSS' (for Microsoft certification) is example of removing child from document (defined in onLoad function). But it doesn't work and throws following exception: Uncaught NotFoundError: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.

I know that if I try to remove child from "outerDiv" node, it will work, but I have no idea why it is written like this in book. It's an mistake in book or I'm doing something wrong?

<!doctype html>
    <html>

    <head>
      <script>  
        window.onload = function () {
          var element = document.getElementById("innerDiv");      
          document.removeChild(element);     
        }
      </script>
    </head>
    <body>
      <div id="outerDiv">
        <p class='mainPara'>Main Paragraph</p>
        <ul>
          <li>First List Item</li>
          <li>Second List Item</li>
          <li>Third List Item</li>
          <li>Fourth List Item</li>
        </ul>
        <div id="innerDiv">
          <p class='subPara' id='P1'>Paragraph 1</p>
          <p class='subPara' id='P2'>Paragraph 2</p>
          <p class='subPara' id='P3'>Paragraph 3</p>
          <p class='subPara' id='P4'>Paragraph 4</p>
        </div>
      </div>
    </body> 
    </html>

Upvotes: 2

Views: 4385

Answers (2)

Vitaliy Terziev
Vitaliy Terziev

Reputation: 6671

This will work for you, element is not direct child of document, so this (your code) will not work.

element.parentNode.removeChild(element)

Upvotes: 1

mrroot5
mrroot5

Reputation: 1951

Try with:

element.parentNode.removeChild(element);

instead of:

document.removeChild(element);

Like @j08691 says, maybe is a book mistake :).

Upvotes: 2

Related Questions