tags:

views:

126

answers:

3

I'm new to DOM and I'm having trouble removing multiple images that I loaded

this loads 7 images (1.jpg, 2.jpg, etc..)

function loadImages() {

    for (var i = 1; i < 8; i++ ) { 
        var img = document.createElement("img"); 
        img.src = "images/"+i+".jpg";
        var idName = "img"+i+"";
        document.getElementById(idName).appendChild(img);
    }
}

this should remove all of them, but doesn't.. I think it breaks at the removeChild line.

function removeImages() {   

    for (var i = 1; i < 8; i++ ) { 
        var idName = "img"+i+"";
        var d = document.getElementById(idName);
        d.removeChild(document.getElementById(img));
    }
}

I think I'm doing something fundamentally wrong, because I don't fully understand how this works...

+1  A: 

In the removeImages function the variable img is not initialized. And even if it was you don't set the id for any of the images in the loadImages function. You could modify your code like this:

function loadImages() {

    for (var i = 1; i < 8; i++ ) { 
        var img = document.createElement("img"); 
        img.src = "images/"+i+".jpg";
        img.id = i;
        var idName = "img"+i+"";
        document.getElementById(idName).appendChild(img);
    }
}

function removeImages() {   

    for (var i = 1; i < 8; i++ ) { 
        var d = document.getElementById(i);
        d.parentNode.removeChild(d);
    }
}
pablochan
A: 

Your code example implies that you're trying to remove a child element of the image and not the image itself. Also, you're using the wrong variable to reference the image. Maybe it works when you replace this line:

    d.removeChild(document.getElementById(img));

With this:

    d.parent.removeChild(document.getElementById(idName));

Also, if you're not that familiar with the DOM tree, you might want to take a look at jQuery, which is more browser-independent than regular DOM instructions.

Prutswonder
A: 

If you are doing DOM manipulation, I would recommend that you use jQuery (or at least try it out).

It will make your life more pleasant, you will be a happier person and it will prevent you from committing harakiri.

Rune
I think you mean seppuku ;]
pablochan
@pablochan: I'm not really into the details. I never tried it :-). BTW, I think your answer is obviously more correct than mine, but the OP should definitely give up on "raw" javascript unless he/she has a reason not to use jQuery or something similar.
Rune
Yeah, JQuery is way cooler than pure JS DOM, but knowing how it works won't hurt :)
pablochan