appendChild not working on divs in a loop - javascript

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>

Related

var numbers = document.querySelectorAll("#box1 , #box2");

I have problem with my javascript code
why that function didn't get the multiple id's
var numbers = document.querySelectorAll("#box1 , #box2");
for(i=0; i<10; i++){
var span = document.createElement('span')
span.textContent = i;
numbers.appendChild(span);
}
/////////////////////////
<div id="box1"></div>(this is the div where is doesn't get)
Unlike jQuery you cannot run an action of the entire node list (array of elements). You have to forEach all the elements.
var numbers = document.querySelectorAll("#box1 , #box2");
numbers.forEach(function(number) {
// this is almost exact copy of your code
for (i = 0; i < 10; i++) {
var span = document.createElement('span')
span.textContent = i;
number.appendChild(span);
}
})
<div id="box1"></div>
<div id="box2"></div>
why dont you use getElementById?
use querySelectorAll when you have many div with same classname
const box1 = document.getElementById("box1")
const box2 = document.getElementById("box2")
const box = document.querySelectorAll(".box")
const box_1 = document.querySelector("#box1")
const box_2 = document.querySelector("#box1")
<div id="box1" class="box"></div>
<div id="box2" class="box"></div>

How to Change Color of Div within a for statement?

Inside my php while loop I output a div with id divborder, and class div-border
Inside that div i have another div with id title
<div id='divborder' class='div-border'>
<div id='Title'>This is Title</div> <br/> video elements
</div>
I have a JavaScript function that get called when the video ends
for (var i = 0; i < videos.length; i++) {
videos[i].addEventListener("ended", function(event)
{
var divBoader2 = document.getElementsByClassName("divborder")[3];
divBoader2.style.borderColor = "#b1ff99";
}
My Question is how do i change the border color of the div and the title of second div?
I can do it like this:
var divBoader2 = document.getElementsByClassName("divborder")[3];
divBoader2.style.borderColor = "#b1ff99";
which works but its not dynamic
Save the value of value at i in another variable declared with let
for (var i = 0; i < videos.length; i++) {
let index = i; //save the value as let so that its binding stays
videos[i].addEventListener("ended", function(event)
{
var divBoader = document.querySelectorAll("div-border")[index];
divBoader.style.borderColor = "#b1ff99";
}
}
Or if the video elements are within the div-border, then use closest
for (var i = 0; i < videos.length; i++) {
videos[i].addEventListener("ended", function(event)
{
var divBoader = event.currentTarget.closest(".div-border");
divBoader.style.borderColor = "#b1ff99";
}
}
A little less verbose code
[...videos].forEach( s => s.closest( ".div-border" ).style.color = "#b1ff99" )
Try this,
Give class name div-border instead of divborder
for (var i = 0; i < videos.length; i++) {
videos[i].addEventListener("ended", function(event)
{
var divBoader2 = document.getElementsByClassName("div-border")[3];
divBoader2.style.borderColor = "#b1ff99";
}
What you need is probably a videos[i].parentNode instead of document.getElementsByClassName("div-border")[3] (see https://developer.mozilla.org/en-US/docs/Web/API/Node/parentNode)

JavaScript: Append content as child of nextSibling

I'm trying append to the next element of multiple divs. So far I have this:
HTML
<pre data-color="blue"></pre>
<div class="yellow></div>
<pre data-color="blue"></pre>
<div class="yellow></div>
<pre data-color="blue"></pre>
<div class="yellow></div>
After the function runs, the content should look like this:
<pre data-color="blue"></pre>
<div class="yellow><p class="content">My content</p></div>
<pre data-color="blue"></pre>
<div class="yellow><p class="content">My content</p></div>
<pre data-color="blue"></pre>
<div class="yellow><p class="content">My content</p></div>
This is my function thus far:
var blue = document.querySelectorAll("[data-color='blue']");
var next = blue.nextSibling;
for (var i=blue.length; i--;) {
var insertdiv = document.createElement('p');
insertdiv.className = 'content';
insertdiv.textContent = 'My Content';
next[i].parentNode.appendChild(insertdiv, blue[i]);
}
Can't get this to work properly though.
No jQuery please.
querySelectorAll returns a list of elements. That list doesn't have a nextSibling property, so your second line gives you undefined in next.
var blues, i, insertDiv;
blues = document.querySelectorAll("[data-color='blue']");
for (i = 0; i < blues.length; ++i) {
if (blues[i].nextSibling) {
console.log(blues[i].nextElementSibling.tagName);
insertDiv = document.createElement('p');
insertDiv.className = 'content';
insertDiv.textContent = 'My Content';
blues[i].nextElementSibling.appendChild(insertDiv);
}
}
There as several logical errors in your code. #T.J. Crowder has described them perfectly.
However, in your case I would rather use CSS next sibling selector in querySelectorAll:
var next = document.querySelectorAll("[data-color='blue'] + *");
for (var i = 0, len = next.length; i < len; i++) {
var insertdiv = document.createElement('p');
insertdiv.className = 'content';
insertdiv.textContent = 'My Content';
next[i].appendChild(insertdiv);
}
DEMO: http://jsfiddle.net/8uywP/
Why don't you just add them to the .yellow divs? Like this:
var yellow = document.getElementsByClassName("yellow");
for (var i=0, l = yellow.length; i<l; i++) {
var insertdiv = document.createElement('p');
insertdiv.className = 'content';
insertdiv.textContent = 'My Content';
yellow[i].appendChild(insertdiv);
}
Working Fiddle example
There is no need to "Traverse" the dom like that if you have a class available on the elements you need.

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

Adding nodes using javascript arrays

I have two arrays var nodes = new Array("alpha","beta","omega");
var childnodes = new Array("one","two","three");. What I want is to create three div elements from nodes array and then add three more div elements to each of the nodes' array div tags so it will look like this.
<div class="alpha">
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
</div>
<div class="beta">
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
</div>
<div class="omega">
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
</div>
How can I achieve this in jquery? My current code does add parent nodes but it does not add child nodes to the parent. How can I make the following code work?
Here is my code
var nodes = new Array("alpha","beta","omega");
var childnodes = new Array("one","two","three");
for (var i = 0; i < nodes.length; i++) {
var parentNodes = "<div class='" + nodes[i] + "'></div>";
console.log(parentNodes);
for (var j = 0; j < childnodes.length; j++) {
var childNodes = "<div class='" + childnodes[j] + "'></div>";
var p = $(parentNodes).attr('class');
console.log($('.' + p).append(childNodes));
$('.' + p).append(childNodes);
console.log(childNodes);
}
$('body').append(parentNodes);
}
Here is jsfiddle code
var nodes = ["alpha","beta","omega"];
var childnodes = ["one","two","three"];
$.each(nodes, function(i, node) {
var div = $('<div>').addClass(node);
$.each(childnodes, function(i, node) {
$('<div>').addClass(node).appendTo(div);
});
div.appendTo('body');
})​
Here is the demo.
Late but another possible example:
var nodes = new Array("alpha","beta","omega");
var childnodes = new Array("one","two","three");
for (var i in nodes) {
var $nodes = $('<div>'+nodes[i]+'</div>');
for(var k in childnodes){
var $child = $('<div>'+childnodes[k]+'</div>');
$child.appendTo($nodes);
}
$nodes.appendTo('#container');
}

Categories

Resources