This is a really simple question but I don't know why it doesn't work.
I have an array with 3 items inside. And I have a container which I would like to insert a number of divs based on the number of items in my array. I used a for loop for this but it is only creating one div. Should it not create 3?
for (var i = 0; i < array.length; i++) {
var container = document.getElementById("container");
container.innerHTML = '<div class="box"></div>';
}
here is a fiddle to demonstrate further fiddle
Move container out of the loop, it is not required inside it.
Append the innerHTML in each iteration.
var container = document.getElementById("container");
for (var i = 0; i < array.length; i++) {
container.innerHTML += '<div class="box"></div>';
}
Edit:
Thanks Canon, for your comments. I also wanted to suggest the same approach as yours, but I got busy in some other work after posting the answer [No excuses :)] Updating the answer:
var htmlElements = "";
for (var i = 0; i < array.length; i++) {
htmlElements += '<div class="box"></div>';
}
var container = document.getElementById("container");
container.innerHTML = htmlElements;
This may look like involving more lines of code but this will be more efficient and less error-prone than the previous solution.
Replace = to +=
As per the #canon comment, edited answer are below
var innerHTMLString = "";
forloop {
innerHTMLString += '<div class="box"></div>';
}
document.getElementById("htmlElements").innerHTML = innerHTMLString
Replace this
container.innerHTML = '<div class="box"></div>';
with this
container.innerHTML += '<div class="box"></div>';
If you want to create more than one, you must call createElement more than once.
d=document.createElement("div");
line into the j loop.
If you call appendChild passing in an element that's already in the DOM, it's moved, not copied.
window.onload=function()
{
var i=0;
var j=0;
for (i=1; i<=8; i++)
{
for (j=1; j<=8; j++)
{
if ((i%2!=0 && j%2==0)||(i%2==0 && j%2!=0))
{
var d=document.createElement("div");
document.body.appendChild(d);
d.className="black";
}
else
{
var d=document.createElement("div");
document.body.appendChild(d);
d.className="white";
}
}
}
}
Javascript Method -
var container = document.getElementById("container");
for (var i = 0; i < array.length; i++) {
container.innerHTML += '<div class="box"></div>';
}
jQuery Method -
foreach(array as value){
$("#container").append('<div class="box"></div>')
}
For further references; what about this approach? :)
HTML:
<div class="particles">
<div class="parts"></div>
</div>
JavaScript:
// Cloning divs where particles go in order not to put 300 of them in the markup :)
const node = document.querySelector(".parts");
[...Array(300)].forEach(_ =>
node.parentNode.insertBefore(node.cloneNode(true), node)
);
Related
My question is:
Is that possible to add the same element without rewriting the same variable.
I am creating a slider, and i need to append a div with a class slide-el into block slider.
Here is a part of code
var body, html, sliderBody, btnLeft, btnRight, i, parts, vHeight, vWidth;
//Variable definitions
var i = 0,
parts = 3,
//Main html elements
body = document.body,
html = document.element,
//viewport Height and Width
vHeight = window.innerHeight,
vWidth = window.innerWidth,
sliderBody = _id("slider"),
btnLeft = _id("btn-left"),
btnRight = _id("btn-right"),
urls = ["http://www.wallpapereast.com/static/images/pier_1080.jpg",
"http://www.wallpapereast.com/static/images/pier_1080.jpg",
"http://www.wallpapereast.com/static/images/pier_1080.jpg",
"http://www.wallpapereast.com/static/images/pier_1080.jpg"];
slide = _createEl("div");
slide.className += "slide-el";
function _id(el){
return document.getElementById(""+ el +"");
}
function _createEl(el){
return document.createElement(""+ el +"");
}
window.onload = function(){
slideLayout();
}
function slideLayout(){
for(var i=0; i < urls.length; i++){
sliderBody.appendChild(slide);
}
}
The problem is that I can't append the same element that many times. It just creates one element instead of 4.
For you to understand better I made a fiddle:
https://jsfiddle.net/ud7dvn3z/
appendChild will remove the node from wherever it is before appending it to its new location, so you need to make copies of the node instead. You can use cloneNode for that. The true makes cloneNode perform a deep clone, i.e. with all its child nodes.
for(var i = 0; i < urls.length; i++){
sliderBody.appendChild(slide.cloneNode(true));
}
Okey guys! I found an answer. I have to put
slide = _createEl("div");
slide.className += "slide-el";
into for loop.
Now it looks like this:
for(var i=0; i < urls.length; i++){
slide = _createEl("div");
slide.className += "slide-el";
sliderBody.appendChild(slide);
}
My question is:
Is that possible to add the same element without rewriting the same variable.
I am creating a slider, and i need to append a div with a class slide-el into block slider.
Here is a part of code
var body, html, sliderBody, btnLeft, btnRight, i, parts, vHeight, vWidth;
//Variable definitions
var i = 0,
parts = 3,
//Main html elements
body = document.body,
html = document.element,
//viewport Height and Width
vHeight = window.innerHeight,
vWidth = window.innerWidth,
sliderBody = _id("slider"),
btnLeft = _id("btn-left"),
btnRight = _id("btn-right"),
urls = ["http://www.wallpapereast.com/static/images/pier_1080.jpg",
"http://www.wallpapereast.com/static/images/pier_1080.jpg",
"http://www.wallpapereast.com/static/images/pier_1080.jpg",
"http://www.wallpapereast.com/static/images/pier_1080.jpg"];
slide = _createEl("div");
slide.className += "slide-el";
function _id(el){
return document.getElementById(""+ el +"");
}
function _createEl(el){
return document.createElement(""+ el +"");
}
window.onload = function(){
slideLayout();
}
function slideLayout(){
for(var i=0; i < urls.length; i++){
sliderBody.appendChild(slide);
}
}
The problem is that I can't append the same element that many times. It just creates one element instead of 4.
For you to understand better I made a fiddle:
https://jsfiddle.net/ud7dvn3z/
appendChild will remove the node from wherever it is before appending it to its new location, so you need to make copies of the node instead. You can use cloneNode for that. The true makes cloneNode perform a deep clone, i.e. with all its child nodes.
for(var i = 0; i < urls.length; i++){
sliderBody.appendChild(slide.cloneNode(true));
}
Okey guys! I found an answer. I have to put
slide = _createEl("div");
slide.className += "slide-el";
into for loop.
Now it looks like this:
for(var i=0; i < urls.length; i++){
slide = _createEl("div");
slide.className += "slide-el";
sliderBody.appendChild(slide);
}
I am attempting to loop through a very simple array in order to create a menu. I have been all around the solution, but have yet to nail it down.
Here's my script:
var json_data = [["Womens","/womens"],["Best Sellers","/best-sellers"]];
var json_length = json_data.length;
var inner_length = 0;
for (var i = 0; i<json_length; i++)
{
inner_length = json_data[i].length;
for( var j = 0; j<inner_length; j++ ){
var innerData = json_data[i][j];
var data = '' + json_data[j][0] + '<br/>';
//alert(data);
$("#content").append(data);
}
}
Basic HTML:
<div id="content">
</div>
When I move the code to append to my div within the first for loop (rather than the second), the second object's data is shown twice rather than the first then second. The current code shows both the first and second object's data, but duplicates it due to being inside the second for loop. I'm sure there is a simple solution, but I am at a loss of ideas.
You can iterate through the array more easily using forEach():
json_data.forEach(function(item) {
var data = '' + item[0] + '<br/>';
$("#content").append(data);
});
Fiddle
Updated your fiddle, removed the unnecessary loop:
https://jsfiddle.net/79k32o1j/4/
for (var i = 0; i<json_length; i++) {
var data = '' + json_data[i][0] + '<br/>';
$("#content").append(data);
}
This code works well but when I start to remove nodes the complete list disappear and I'm left with one node in the innerHTML, instead of removing one by one gradually which is what I want. To leave a few to none behind perhaps gradually instead of straight one for all displayed in the innerHTML, of the div that displays the removal sort of say... I can perfectly do this to work using arrays but I'm curious if there's an way out without using any(arrays)?
HTML code
<button onClick="remov()">remove</button>
<button onClick="addDiv()">Add Div</button>
<div>
<div></div>
<div></div><div></div>
<div></div>
</div>
<div id="tt"></div>
Javascript Code
var stage = document.getElementsByTagName("div")[0];
var tt = document.getElementById("tt");
function remov() {
if (stage.hasChildNodes()) {
stage.removeChild(stage.firstChild);
for (var i = 0; i < stage.childNodes.length; i++) {
tt.innerHTML = stage.childNodes[i].nodeName;
}
if (!stage.hasChildNodes()) {
tt.innerHTML = "no nodes";
}
}
}
for (var i = 0; i < stage.childNodes.length; i++) {
tt.innerHTML += stage.childNodes[i].nodeName;
}
function addDiv() {
var a = document.createElement("div");
stage.appendChild(a);
if (!stage.hasChildNodes()) {
tt.innerHTML += stage.firstChild.nodeName;
} else {
tt.innerHTML += stage.lastChild.nodeName
}
}
jsfiddle
If you want to display all divs during their removal need to change = to += as below
function remov() {
tt.innerHTML=''; //EDIT forgot to add in this line
if (stage.hasChildNodes()) {
stage.removeChild(stage.firstChild);
for (var i = 0; i < stage.childNodes.length; i++) {
tt.innerHTML += stage.childNodes[i].nodeName; //<------- + needed to display all divs
}
if (!stage.hasChildNodes()) {
tt.innerHTML = "no nodes";
}
}
}
EDIT Fiddle added
I want to get all DIVs in DIV(id = room) and do the same javascript code on each one.
I think it should look like this
Get element by id room -> Get all divs inside -> do something on them(change each class to "grass")
or by using a loop.
How to do that?
Please don't use jQuery.
Modern browsers (IE9+):
var divs = document.querySelectorAll('#room div');
[].forEach.call(divs, function(div){
div.className = 'green';
});
var a = document.getElementById("room").getElementsByTagName("div");
for(i = 0; i < a.length; i++)
{
a[i].className = "grass";
}
Do you want to get all divs inside, or just direct children?
This one traverses direct children. If you want to go through all internal nodes, you need to recurse it.
function grassify(nodeId) {
var node = document.getElementById(nodeId);
for(var i in node.childNodes) {
// Do things with node.childNodes[i], for example:
node.childNodes[i].className = 'grass';
}
}
Then just:
grassify('room');
var room=document.getElementByID("#room");
var divs=room.getElementsByTagName("div");
for(var i=0;i<divs.length;i++){
doSomething(divs[i]);
}
Use getElementByID and getElementsByTagName
Use getElementsByTagName
First get a reference to the container element, then use getElementsByTagName for the type of element you want.
See http://jsfiddle.net/aQtTx/
JS:
var targetDiv = document.getElementById("div1");
var nestedDivs = document.getElementsByTagName("div");
for(var divIndex = 0; divIndex < nestedDivs.length; divIndex++)
{
nestedDivs[divIndex].style.backgroundColor = 'red';
}
function myFunction()
{
var a=document.getElementById('room').childNodes;
for (i=0; i<a.length; i++)
{
a[i].className="grass";
};
}
JsFiddle
var parent = document.getElementById("room");
var divs = parent.getElementsByTagName('div');
for (i=0; i<divs.length; i++)
{
divs[i].className="grass";
};