Reputation:
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();
}
Upvotes: 4
Views: 1559
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
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;
Upvotes: 0
Reputation: 396
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
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