1

I'm trying to add/remove a DOM element (id ="result") dynamically. The addition seems to work fine but after removal the element still appears on the page.

What's happening here? What am I doing wrong?

Here is my code:

<!DOCTYPE html>
<html>
  <body>
    <script>
      function clearResult() {
        if (document.getElementById("result") != null){
            alert("remove #result");
            $("#result").remove();
            if (document.getElementById("result") != null) {
                alert("#result still exists");
            }
        }
        alert("Exiting clearResult");
      }

      function search() {
        clearResult();
         if (document.getElementById("result") == null) {
            alert("add #result");
            $('<table id="result"><tr>I am a table</tr></table>').appendTo('#ex');
         }                  
      }      
    </script>

    <div>
      <button id="search" onclick="search()" value="Send">Search</button>
    </div>     
    <div id="ex">
      @*Add result table here dynamically*@
    </div>

  </body>
</html>
NGambit
  • 1,141
  • 13
  • 27

1 Answers1

5

Your HTML is invalid. Content within a table needs to be in td tags. Without those, your code is being rendered as:

I am a table
<table id="result"><tr></tr></table>

You can see that then removing the #result element appears to do nothing, because the text does not disappear. If you change your code to include the td elements, it works fine:

$('<table id="result"><tr><td>I am a table</td></tr></table>').appendTo('#ex');

Example fiddle


Note that you can also massively simplify your code. You don't need to check for the existance of an element before removing it in jQuery. Also, you should use jQuerys event handlers, instead of outdated on attributes. Try this:

<div>
    <button id="search" value="Send">Search</button>
</div>
<div id="ex"></div>
$('#search').click(function() {
    $('#ex').empty().append('<table id="result"><tr><td>I am a table</td></tr></table>');
});

Updated fiddle

I use empty() here on the #ex element to save a selector, it has the same behaviour as remove(), except is performed on the children of an element, not the element itself.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339