tiger tiger - 6 months ago 13
Javascript Question

Remove element using remove(), but its property still exist

I have a problem with

remove()
. After I remove the
<svg>
, its property still exist, I want to delete it completely. The properties such as position, and other css property. If I can have some explanations about
remove()
and
empty()
, it will be more appreciated. Thank you very much for the help.

My code:



$(document).ready(function() {
$('#play').click(function() {
$('#container svg').remove();
});
$('#test').text($('#svg1').position().left)
}); // end ready

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container" style="width:600px; height: 400px">
<svg height="130" width="150" style="position:absolute; left:200; top:200;" class="ui-widget-content" id="svg1">
<text fill="black" x=75 y=75 style="text-anchor: middle">1</text>
<path d="M38 0 L113 0 L150 65 L113 130 L38 130 L0 65 Z" / fill="none" stroke="blue">
</svg>
</div>
<button id="play">Play</button>
<h1 id="test"></h1>




Answer

You are getting initial position of svg because your code is placed directly in document ready. When you put this code

$('#test').text($('#svg1').position().left)

inside your click event handler and look at the console output, you'll see:

Uncaught TypeError: Cannot read property 'left' of undefined

So, it means, that the element along with all its properties is removed. Though, the text of #test element won't change because of the above js error.

$(document).ready(function() {
  $('#play').click(function() {
    $('#container svg').remove();
    $('#test').text($('#svg1').position().left)
  });
  
}); // end ready
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container" style="width:600px; height: 400px">
  <svg height="130" width="150" style="position:absolute; left:200; top:200;" class="ui-widget-content" id="svg1">
    <text fill="black" x=75 y=75 style="text-anchor: middle">1</text>
    <path d="M38 0 L113 0 L150 65 L113 130 L38 130 L0 65 Z" / fill="none" stroke="blue">
  </svg>
</div>
<button id="play">Play</button>
<h1 id="test"></h1>