user3421904
user3421904

Reputation:

How to remove children in JavaScript

What is the equivalent of the following JQuery code in JavaScript:

$('div').children().remove();

I tried following but it says length is not defined:

var nodes = document.getElementsByTagName('div').childNodes;
for(var i=0; i< nodes.length; i++) {

         nodes[i].remove();

}

Fiddle

Upvotes: 4

Views: 1559

Answers (4)

VisioN
VisioN

Reputation: 145398

The correct cross-browser way to remove elements in pure JavaScript is:

element.parentNode.removeChild(element);

So following your example the solution is this:

var nodes = document.getElementsByTagName('div');
for (var i = 0, len = nodes.length; i < len; i++) {
    var node = nodes[i],
        children = node.childNodes;

    for (var j = children.length; j--;) {
        node.removeChild(children[j]);
    }
}

However, better option to remove all children is to do it in while loop:

var nodes = document.getElementsByTagName('div');
for (var i = 0, len = nodes.length; i < len; i++) {
    var node = nodes[i];
    while (node.firstChild) {
        node.removeChild(node.firstChild);
    }
}

DEMO: http://jsfiddle.net/N6RM4/1/

Upvotes: 5

alexP
alexP

Reputation: 3765

getElementsByTagName returns a element-list and you have to specify the index (in your case [0])

var nodes = document.getElementsByTagName('div')[0].childNodes;

JSfiddle

Upvotes: 0

Kvothe
Kvothe

Reputation: 396

This is a working example

HTML

<button id="adds" onclick="add()">add</button>
<button id="removes" onclick="del()">remove</button>
<form>
    <div id="myList">
        <div><input type="checkbox"></div>
    </div>
</form>

JS

function del(){
    var list=document.getElementById("myList");
    if (list.childNodes.length > 2){
        list.removeChild(list.childNodes[list.childNodes.length-1]);
    }
}


function add(){
    var par=document.createElement("div");
    var chi = document.createElement('div');    
    chi.innerHTML = '<input type="checkbox"></input>';
    par.appendChild(chi);
    document.getElementById("myList").appendChild(par);
}

Upvotes: 0

G&#225;bor Buella
G&#225;bor Buella

Reputation: 1920

Check document.getElementsByTagName('div')

It returns a NodeList

This has no member called childNodes

To remove all childnodes of all divs, you need to iterate over these nodes.

Upvotes: 0

Related Questions