How to add DOM Element in for loop - javascript

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

Related

How to give unique ids to each child div created dynamically?

The function displays eight elements on click in dynamically created divs using the slice() method. How can I give a unique id to each div? Your suggestions would be of great help to me.
var words = [40];
var count = 0;
var x = "";
function nextElems() {
var newArray = words.slice(count, count + 8);
for (i = 0; i < newArray.length; i++) {
x += '<div class=box>' + newArray[i] + '</div>';
document.getElementById('container').innerHTML = x;
}
x = "";
count += 8;
}
I have tried this but it's not working:
var mainDiv = document.getElementById('container');
var first = mainDiv.getElementsByTagName('div')[0];
first.id = 'one';
You can do it right inside the for loop while it's iterating:
for (i = 0; i < newArray.length; i++)
{
x += '<div id="box-' + i + '"> class="box">' + newArray[i] + '</div>';
document.getElementById('container').innerHTML = x;
}
You can use assign an ID inside the text string.
Here are a couple of other things you can do to improve this code:
Move the getElementById outside the loop
use js methods instead of string concatenation
Something like this (untested):
// get the container
container = document.getElementById('container');
for (i = 0; i < newArray.length; i++)
{
// create a div
var div = document.createElement('div');
// add attributes
div.setAttribute("id", "box-" + i);
div.setAttribute("class", "box");
// create text node
var textnode = document.createTextNode("This is div #" + i);
// add text to div
div.appendChild(textnode);
// append to container
container.appendChild(div);
}
How about giving it the id when creating? Also put the class=box in quotations like so -> class="box".
And add the whole div construct only once after the for loop. Because right now you are basically overwriting the whole thing multiple times.
var words = [40];
var count = 0;
var x = "";
function nextElems() {
var newArray = words.slice(count, count + 8);
for (i = 0; i < newArray.length; i++)
{
// Change class and add custom id
x += '<div class="box" id="box-'+i+'">' + newArray[i] + '</div>';
}
document.getElementById('container').innerHTML = x; // Add divs after for loop
x = "";
count += 8;
}
Now each box has a unique id going from box-0, box-1, ... to box-n

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)

Children loop html append into parent loop inserted div by javascript

The loop working but don't getting class as a selector from parent loop generated div...
var parentdiv = $(".pDiv");
for (i = 0; i < 3; i++) {
$(parentdiv).append("<label class="
addLabel ">" + i + "</label>"); // parent loop add
for (j = 0; j < 3; j++) {
$(".addLabel").append("<label class="
addLabel2 ">" + j + "</label>"); //children loop in parent class
}
}
First of all, your text has too many mistakes and it's hard to understand what exactly is the problem.
Secondly - your string in append() function is not concatenated properly as addLabel doesn't seem to be a variable. Try this:
$(parentdiv).append("<label class='addLabel"+ i +"'></label>") and
$(".addLabel").append("<label class='addLabel"+ j +"'></label>");
The problem solved the children loop :
//children loop start
for (var c = 0; c < checkBoxs.length; c++) {
// Things[i]
console.log(c);
var multiInputs = $("#myframe1").contents().find(".div2"); // iframe parent div
var putIntoParent = $(multiInputs).children(); // selector as parent children
var getMultiInput = multiInputs.selector;
//$(multiInputs).append('<lable><input type="checkbox"/>'+ checkBoxs[c].label +' </label>');
var node = document.createElement('span');
//var inputPlace = document.querySelector('.inputField_add');
console.log(multiInputs)
// $(multiInputs).on("load", function() {
$(putIntoParent).append('<lable><input type="checkbox"/>'+ checkBoxs[c].label +' </label>');
// });
}

Looping through a set of <p>'s one at a time

I'm trying to figure out how to count the number of p's so every time the button is pressed, it outputs to 0 to 1 until the maximum number of p's is counted.
var big_number = 999999;
var i;
var a = document.getElementsByTagName("p");
function function0() {
for (i=0; i < big_number; i++) {
document.getElementsByTagName("p")[i].innerHTML="text";
}
}
I want it to write to another p every time the button is pressed.
document.getElementsByTagName("p").length // number of p elements on the page
Is that what you were asking?
Make a generic tag adder function then call it:
function addTags(tagName,start, max, container) {
var i = start;
for (i; i < max; i++) {
var newp = document.createElement(tagName);
newp.innerHTML = "paragraph" + i;
container.appendChild(newp);
}
}
var tag = 'p';
var big_number = 30;
var i;
var a = document.getElementsByTagName(tag );
// **THIS is your specific question answer**:
var pCount = a.length;
var parent = document.getElementById('mydiv');
addTags(tag,pCount , big_number, parent);
// add 10 more
a = document.getElementsByTagName(tag );
pCount = a.length;
big_number = big_number+10;
addTags(tag,pCount , big_number, parent);
EDIT:
NOTE: THIS might be better, only hitting the DOM once, up to you to determine need:
function addTagGroup(tagName, start, max, container) {
var tempContainer = document.createDocumentFragment();
var i = start;
for (i; i < max; i++) {
var el = document.createElement(tagName);
el.textContent = "Paragraph" + i;
tempContainer.appendChild(el);
}
container.appendChild(tempContainer);
}
To find out how many <p> elements there are in the document you should use DOM's length property as below :-
var numP = document.getElementsByTagName("P").length;
or
var div = document.getElementById("myDIV");
var numP = div.getElementsByTagName("P").length;
To get number of element inside a tag.

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