How to remove children in JavaScript - 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

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/

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.

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);
}

getElementsByTagName returns a element-list and you have to specify the index (in your case [0])
var nodes = document.getElementsByTagName('div')[0].childNodes;
JSfiddle

Related

Change all <p> elements with a class to <code>

This is working fine using the document.getElementsByID, but how do you change all the p tags with a prgrph class to code so that instead of <p class="prgrph"></p> there will be <code class="prgrph"></code>?
var b = document.querySelectorAll('p');
for (var i = 0; i < b.length; i++) {
b[i].setAttribute('id', 'prgrph');
}
But this is not working:
function changeTagName(el, newTagName) {
var n = document.createElement(newTagName);
var attr = el.attributes;
for (var i = 0, len = attr.length; i < len; ++i) {
n.setAttribute(attr[i].name, attr[i].value);
}
n.innerHTML = el.innerHTML;
el.parentNode.replaceChild(n, el);
}
changeTagName(document.getElementsByClassName('prgrph'), 'code');
I tried to use document.getElementsByClassName and it's giving me error on the attr.length:
Uncaught TypeError: Cannot read property 'length' of undefined
IDs need to be unique and you likely want to change the P tags one by one
I am not sure why you first loop over the P tags and then loop again; the first loop is not really needed if the second loop selects the P tag instead of the class
var b = document.querySelectorAll('p');
for (var i = 0; i < b.length; i++) {
b[i].classList.add('prgrph');
}
function changeTagName(el, newTagName) {
var n = document.createElement(newTagName);
var attr = el.attributes;
for (var i = 0, len = attr.length; i < len; ++i) {
n.setAttribute(attr[i].name, attr[i].value);
}
n.innerHTML = el.innerHTML;
el.parentNode.replaceChild(n, el);
}
document.querySelectorAll(".prgrph").forEach(function(p) { // not IE
changeTagName(p, 'code');
})
code {
color: red
}
<p data-attr="one">Paragraph 1</p>
<p data-attr="two">Paragraph 2</p>
<p>Paragraph 3</p>

appendChild not working on divs in a loop

I am trying to append new div elements to existing divs by using document.getElementsByTagName("div"), converting it to an array, then using appendChild on it. However, when I inspect the frame source of this jsfiddle, it doesn't seem to append it to the divs. It is just:
<body>
<div id="1">
<div id="2">
test
</div>
</div>
Instead of the expected result:
<body>
<div id="1">
<div id="2">
test
</div><div></div>
</div><div></div>
https://jsfiddle.net/ng58e87w/
var allDivs = [].slice.call(document.getElementsByTagName("div"));
for (var i = 0; i < allDivs.length; i++) {
var newDiv = document.createElement("div");
allDivs[i].appendChild(newDiv);
console.log(allDivs[i]);
}
I can't comment, but I believe you are just creating empty divs and adding nothing to them. They show up created when you inspect element in the jsfiddle. I also set their text to something and it seemed to work.
var allDivs = [].slice.call(document.getElementsByTagName("div"));
for (var i = 0; i < allDivs.length; i++) {
var newDiv = document.createElement("div");
newDiv.innerHTML = "Hidden Div?";
allDivs[i].appendChild(newDiv);
console.log(allDivs[i]);
}
Use .after() instead of .appendChild().
var words = ['apple','banana','cake'];
console.log(words[0]);
object1 = {
name:'frank',
greet:function(){
alert('hello '+this.name)
}
};
object2 = {
name:'andy'
};
// Note that object2 has no greet method.
// But we may "borrow" from object1:
object1.greet.call(object2);
/*
var divs = [];
var arr = Array.prototype.slice.call( document.getElementsByTagName("div") );
for(var i = 0; i < arr.length; i++) {
//do something to each div like
var div = document.createElement("div");
arr[i].appendChild(div);
}
*/
var allDivs = [].slice.call(document.getElementsByTagName("div"));
for (var i = 0; i < allDivs.length; i++) {
var newDiv = document.createElement("div");
allDivs[i].after(newDiv);
console.log(allDivs[i]);
}
<div id="1">
<div id="2">
test
</div>
</div>

Instantiate new element class using javascript

How can I instantiate an existing div element using javascript? Lets say I have:
<div class="container">
<div class="myclass">TROLL FACE</div>
</div>
I want to create as many 'myclass' element inside the 'container' class as I want using javascript. How can I do this?
Please help, thanks.
You may want the .clone method.
var ele = $('.myclass');
for (var i = 0; i < 5; i++) {
ele.clone().appendTo('.container');
}
The live demo.
var container = $('.container');
for (var i = 0; i < 5; i++) {
container.append('<div class="myclass">TROLL FACE</div>');
}
You could use the .append() method.
With or without JQuery:
for (var i = 0; i < howMany; ++i) {
// pure js
var div = document.createElement('div')
div.classList.add('myclass')
somePlace.appendChild(div)
// jquery
$("<div></div>").addClass('myclass').appendTo(somePlace)
}
Try this
<div class="container">
<div class="myclass">TROLL FACE</div>
</div>
var $container = $('.container');
var $myclass = $('.container').html();
var mycount ; // Your count
for(var i =0;i< mycount ; i++){
$container.append($myclass)
}

How to add DOM Element in for loop

How can I create new Element each time when (i) will be incremented:
for(int i = 0; i < 10; i++)
{
Element child = doc.createElement("xxx");
root.setAttribute("x", i * "xx");
doc.appendChild(child);
}
Using pure js
var div = document.getElementById("main");
for (var i = 0; i < 10; i++) {
var span = document.createElement("span");
span.setAttribute("class", "new");
span.innerHTML = "span" + i;
div.appendChild(span);
}​
HTML
​<div id="main"></div>​​​​​​​
Working example.
Cheers!!
Using java
Element child = null;
for(int i = 0; i < 10; i++)
{
child = doc.createElement("xxx" + i);//you can write a method with int parameter to get element name from somewhere else
doc.appendChild(child);
}
I hope this is what you wanted, by the way for text nodes you should use doc.createTextNode("A")

What's the equivalent of this in plain JavaScript?

$('<span class="pictos">j</span>').prependTo('li');
var li = document.getElementsByTagName('li');
for (var i = 0; i < li.length; i++) {
var e = document.createElement('span');
e.className = 'pictos';
e.appendChild(document.createTextNode('j'));
li[i].insertBefore(e, li[i].firstChild);
}
Working example on JSBin
What jQuery actually does is take the element and clone it for each parent it needs appending to which is a bit faster, like this:
var span = document.createElement('span');
span.className = 'pictos';
span.appendChild(document.createTextNode('j'));
var lis = document.getElementsByTagName('li');
for (var i = 0; i < lis.length; i++) {
lis[i].insertBefore(span.cloneNode(true), lis[i].firstChild);
}​
You can test it out here.

Categories

Resources