eow2898 eow2898 - 2 months ago 12
CSS Question

how to remove elements in document fragment after append

I'm working on a javascript project in which I use a document fragment to append several span elements at once. Then they are animated with css.

.redCircle {
float: left;
height:20px;
width:20px;
border-radius:10px;
box-shadow: 0 0 20px red;
background-color: red;
animation: 2s circleFall linear;
}

@keyframes circleFall {
0%{margin:0;}
100%{margin:100% 10%;}
}


setInterval(thingyTime, 5000);

function thingyTime() {
var count = 15,
spanVar = document.createElement("span"),
fragment = document.createDocumentFragment();

for (var i = 0; i < count; ++i) {

for (var j = 0; j < 1; ++j) {
spanVar = document.createElement('spanVar');
spanVar.className = "redCircle";
fragment.appendChild(spanVar);
}
}

document.body.appendChild(fragment);

};

thingyTime();


I'm trying to figure out how to remove the spans after the animation is completed. I have used

setTimeout(function(){

spanVar.remove(spanVar.selectedIndex);

},2000); // <= animation length


and it works fine when it's only for one element, but I need to remove all the elements in the fragment.

I aprreciate your help.

Answer

A few bits (further to my initial comment). For generating, I'd drop the extra createElement("span") at the top, since it never gets used. Then create span's in the loop, rather than spanVar's (assuming the are unwanted). For the create element method you just give it the element type you want it to make.

function thingyTime() {
    var count = 15,
        spanVar,
        fragment = document.createDocumentFragment();

    for (var i = 0; i < count; ++i) { 
        for (var j = 0; j < 1; ++j) { 
            spanVar = document.createElement('span');
            spanVar.className = "redCircle";
            fragment.appendChild(spanVar);
        }
    }
    document.body.appendChild(fragment);
};

For cleanup, easiest way is just use the class you created. Query for em all, & then nuke em one by one.

document.querySelectorAll(".redCircle").forEach(function(c){
    c.parentNode.removeChild(c);
});

If you have other instances of the redCircle you don't want to nuke on the other hand. I'd add a var circlesToCleanup = []; then in the creation loop push each of em on to it circlesToCleanup.push(spanVar)

Then when you call your cleanup, iterate circlesToCleanup rather than the querySelector output.