Adding nodes using javascript arrays - javascript

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

Related

How copying elements without deleting originals?

I have a loop to duplicate an array, and another to add copy in another div.
Both loop work good but original element are deleted, someone can explain me why?
And how can i fixe it? Thank you!
var mesElements = document.querySelectorAll('.element');
var catchCopy = document.querySelector('.parent_copy');
var mesElementsCopie = []
for(var j = 0; j < mesElements.length; ++j){
mesElementsCopie[j] = mesElements[j];
}
for(var k = 0; k < mesElements.length; ++k){
catchCopy.appendChild(mesElementsCopie[k]);
}
<div class="parent_element" style="background-color: red;">
<div class="element">text</div>
<div class="element">text</div>
<div class="element">text</div>
</div>
<div class="parent_copy" style="background-color: green;"></div>
On this line, you do not copy the node, but rather you create two references to the same DOM node:
mesElementsCopie[j] = mesElements[j];
You should use the cloneNode() method:
mesElementsCopie[j] = mesElements[j].cloneNode(true);
Here's the fixed code:
var mesElements = document.querySelectorAll('.element');
var catchCopy = document.querySelector('.parent_copy');
var mesElementsCopie = []
for(var j = 0; j < mesElements.length; ++j){
mesElementsCopie[j] = mesElements[j].cloneNode(true);
}
for(var k = 0; k < mesElements.length; ++k){
catchCopy.appendChild(mesElementsCopie[k]);
}
<div class="parent_element" style="background-color: red;">
<div class="element">text</div>
<div class="element">text</div>
<div class="element">text</div>
</div>
<div class="parent_copy" style="background-color: green;"></div>
You were adding the same elements you had grabbed from the parent element, so it was just moving them to the parent copy. Use .cloneNode(true) to make sure you're not using the same element.

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>

How to wrap for loop in a div?

I have been stuck on this silly thing, I can't figure out how to wrap my for loop inside of a div.
for (item = 0; item < event.length; item++) {
var ID = event[item].id;
element.find(".title").after("<span class='id'><img src='/avatar/" +ID+ "'/></span>");
}
I want to achive this:
<div>
<span></span>
<span></span>
<span></span>
</div>
Any Help is much apprciated.
Hope this snippet will be useful
// a variable for the dynamically created span
var spanString = "";
for (item = 0; item < event.length; item++) {
var ID = event[item].id;
// new string will con cat wit the spanString
spanString += ("<span class='id'><img src='/avatar/" + ID + "'/></span>");
}
// append the spanString to the `div.title`
$(".title").append($(spanString))
$(document).ready(function() {
//Assume sample event array
var event = [1, 2, 3];
for (item = 0; item < event.length; item++) {
var ID = event[item];
$("<span class='id'><img src='/avatar/" +ID+ "'/></span<br>").appendTo('#name');
};
});
Considering sample HTML Below
<div id="name">
hello
</div>
This way you can populate content inside the div

.getAttribute() method on elements returned by querySelectorAll()

I'm trying to get the value of data attributes from multiple div elements. The elements are captured into a variable using
querySelectorAll()
I'm getting an error when I loop through the variable that contains the element and use the getAttribute() Method:
<div id="container">
<div class="box" data-speed="2" id="one"></div>
<div class="box" data-speed="3" id="two"></div>
<div class="box" data-speed="4" id="three"></div>
<div class="box" data-speed="5" id="four"></div>
<div class="box" data-speed="6" id="five"></div>
</div>
js:
(function() {
var boxes = document.getElementsByClassName("box");
for (var i = 0; i < boxes.length; i++) {
var r = Math.floor((Math.random() * 254) + 1);
boxes[i].style.background = "rgba(" + r + "," + i*30 + "," + i*45 + ", 1)";
}
})();
var divArray = [];
var divs = document.querySelectorAll(".box");
for (i = 0; i <= divs.length; i++) {
console.log(divs[i]);
var speed = parseInt(divs[i].getAttribute("data-speed"));
};
Jsfiddle https://jsfiddle.net/kshatriiya/L8xsvzL1/1/
When I
console.log(divs[i])
it shows the element, I don't know why I'm unable to use the attribute method on it.
Any pointer would be really appreciated!
Arrays in javascript are 0 index based
use
for (i = 0; i < divs.length; i++) {
instead of
for (i = 0; i <= divs.length; i++) {
due to this you are getting last divs[i] as undefined and thats why console display that error
updated fiddle : https://jsfiddle.net/n3qhan4e/
It's simple
document.querySelectorAll('.box').forEach(elem => console.log(elem.getAttribute('data-speed')));

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

Categories

Resources