JTrixx16
JTrixx16

Reputation: 1173

Removing a child element in a container using removeChild() does not work

I've created a sample file that has adding and removing children elements in a mother element. The adding was successful, but I'm having a problem in removing children elements. The goal is every single click of remove button removes a child element.

 var adds = document.querySelector('#add');
    var remove = document.querySelector('#remove');
    var section = document.querySelector('section');
    var div;
    
    adds.onclick = function() {
    	div = document.createElement('div');
    	section.appendChild(div);
    	div.classList.add('style');
    };
    
    // THE PROBLEM
    remove.onclick = function() {
    	while(section.children.length !== 0) {
    		for(var c in section.children) {
    			section.removeChild(div[c]);
    		}
    	}
    };
  section {
        display: flex;
    	background: #0ff;
    	height: 100px;
    	padding: 8px;
    }
    section > div {margin: 0 1px;}
    .style {
    	width: 100px;
    	height: 100px;
    	background: lightgreen;
    }
<button id="add">Add</button>
    <button id="remove">Remove</button>
    
    <section class="container"></section>
<br>

What's wrong with my code?

Upvotes: 1

Views: 1891

Answers (1)

gurvinder372
gurvinder372

Reputation: 68433

What's wrong with my code?

This line

section.removeChild(div[c]);

div could be undefined here and anyways, sections's children are not necessarily div's children

so change it to

section.removeChild(section.children [c]);

Also, while is not necessary

remove.onclick = function() {
        for(var c in section.children) {
            section.removeChild(section.children[c]);
        }
};

EDIT

The goal is every single click of remove button removes a child element.

remove.onclick = function() {
        if(section.children length ) {
            section.removeChild(section.children[0]);
        }
};

changed for with if

Upvotes: 4

Related Questions