Tobias Baumeister
Tobias Baumeister

Reputation: 2147

JS: Can't remove created Element in IE

I'm dynamically creating an image via javascript like this:

var dragimg = null;
function createImage(g) {
    dragimg = document.createElement("img");
    dragimg.src = "link/to/image.png";
    dragimg.style.width = "50px";
    dragimg.style.position = "absolute";
    dragimg.style.zIndex = 100;
    $("body").prepend(dragimg);
}

After creating the Image, I want to remove it at some point by calling this function:

function removeImage() {
dragimg.remove();
}

This works well in Chrome, Firefox & Opera. However, it doesn't work in Internet Explorer 11.

I'd also like to point out I have an document.onmousemove function set which manipulates the left and top attribute of the created image when the mouse moves. This works well in all browsers - but I'm not sure if it has something to do with the remove-problem.

I've also tried to remove the image by dragimg.parentNode.removeChild(dragimg), but same result.

Upvotes: 1

Views: 1010

Answers (3)

Prabu
Prabu

Reputation: 4187

I'm not sure the context where you are calling the removeImage function, but the code below demonstrates inserting the image element and removes it after an interval of 2 seconds.

Note: Replace the path to your image.

<html>
<head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
    <script type="text/javascript">
        var dragimg = null;
        function createImage(g) {
            dragimg = document.createElement("img");
            dragimg.src = "someimage.jpg";
            dragimg.style.width = "50px";
            dragimg.style.position = "absolute";
            dragimg.style.zIndex = 100;
            $("body").prepend(dragimg);
        }

        function removeImg() {
            dragimg.parentNode.removeChild(dragimg);
        }

        createImage(null);
        window.setInterval(removeImg, 2000);
    </script>
</body>
</html>

Upvotes: 0

Lim H.
Lim H.

Reputation: 10050

A few things other than the classic just-use-jquery answer:

  1. element.remove() is not supported yet by Internet Explorer, according to the API: http://msdn.microsoft.com/en-us/library/ie/hh772117(v=vs.85).aspx. It's an experimental technology: https://developer.mozilla.org/en-US/docs/Web/API/ChildNode.remove
  2. Are you sure parentNode.removeChild isn't working because it is for me: http://jsfiddle.net/limdauto/wztm1dgk/

Before enter image description here

After enter image description here

Upvotes: 3

skobaljic
skobaljic

Reputation: 9634

To use jQuery remove method you need this:

function removeImage() {
    $(dragimg).remove();
}

Your dragimg is a dom element, but $(dragimg) is a jQuery element. While jQuery prepend method accepts dom elements, remove does not - it applies to jQuery element itself or to selector. More about jQuery remove and prepend.

Upvotes: 1

Related Questions