document.getElementByID and for loop - javascript

<button id="mybtn">click me for index </button>
My JavaScript code:
var myarray = [2,4,6,5,5];
(i=0; i<= myarray.length; i++){
var allBtn = document.getElementByID("mybtn");
document.body.appendChild(allBtn);
}
I want to make multiple buttons, so i have used for loop to create those. but it is not working.
Here is the url: http://jsbin.com/donafuluha/1/edit?html,js,console,output

You can make use of cloneNode in order to append existing elements
Working Demo
Code:
var myarray = [2,4,6,5,5];
for(var i=0; i< myarray.length; i++){
var allBtn = document.getElementById("mybtn").cloneNode(true);
document.body.appendChild(allBtn);
}

you can use cloneNode() to copy it and append multiple. I also recommend you remove the node from the DOM and only show the clones on the screen. And looking at your array it seems you want to attach some data too. This is done by either assigning a property or using .setAttribute("name",value)
var myarray = [2,4,6,5,5];
var proto = document.getElementById("mybtn");
proto.parentElement.removeChild(proto);
for(var i=0; i<myarray.length; i++){
var allBtn = proto.cloneNode(true);
allBtn.setAttribute("data-index", myarray[i]);
document.body.appendChild(allBtn);
}

You should try following code snippet it will solve your problem
var myarray = [2,4,6,5,5];
for(var i=0; i<= myarray.length; i++){
var btn = document.createElement("BUTTON");
var t = document.createTextNode("New Button"+(i+1));
btn.appendChild(t);
document.body.appendChild(btn);
}

Related

Replace a default link with another link

I want change the link attribute href of an existing link with another link using JavaScript. How can I do this?
Here is the link:
See moreSee moreSee more
I have tried the following but it doesn't work:
var links = document.getElementsByTagName('a');
var len = links.replace;
for(var i=0; i<replace; i++){
links[i].href = "newlink.php?+BLABLABAL";
}
Replace links.replace by links.length, since you are iterating over the links array.
Working code:
// This is an array of links
var links = document.getElementsByTagName('a');
// The length of the array
var len = links.length;
// Iterate over the array
for(var i = 0; i < len; i++){
links[i].href = "https://twitter.com";
}
Working demo: http://codepen.io/anon/pen/yYBdgQ
Change your js code with this :
var links = document.getElementsByTagName('a');
var len = links.length;
for(var i=0; i<len; i++){
links[i].href = "newlink.php?+BLABLABAL";
}
You have to take the length of links in var len, and then run the loop through len

Dynamic created variables inside for loop, Javascript

Creating static variables is not an option in this case becouse it would take to long time and ineffective to what im trying to accomplish. I have an Array with images and I'm trying to create a way to make divs according to the length of the array. 1,2,3,4 etc.
var images = ['image1.JPG', 'image2.JPG', 'image3.JPG'];
var totalimages = images.length;
Which will result in an array length of 3. I would like to create 3 variables for this.
for (var i = 0; i > totalimages; i++){
var div[i] = document.createElement('div');
}
This seems not to be working for some reason. I tried to create a div array/list outside the for loop aswell.
var div = [];
for (var i = 0; i > totalimages; i++){
var div[i] = document.createElement('div');
}
Still not working. I dunno why this is not working. Javascript only
EDIT: (not working) i mean it gives me syntax error.
You have defined div already. In loop you shouldn't be saying like var div again.
BTW var div[ will cause a syntax error.
Use this
div[i] = document.createElement('div');
instead of
var div[i] = document.createElement('div');
Any way I'll prefer saying this at that place
div.push(document.createElement('div'));
And this will cause i > totalimages an infinitive loop, say i < totalimages instead.
i < totalimages
not
i > totalimages
Make sure you don't use var inside the array if you're assigning new values:
var div = [];
for (var i = 0; i < totalimages; i++){
div[i] = document.createElement('div');
}
DEMO
In short:
var images = ['image1.JPG', 'image2.JPG', 'image3.JPG'];
var totalimages = images.length;
var div = [];
for (var i = 0; i < totalimages; i++){
div.push(document.createElement('div'));
}

Two different types of NodeLists? Cannot set properties on one NodeList to Array

These two examples are both node lists, but only the first works.
Works as expected:
var apple = document.getElementById('apple');
var nodeList = document.getElementsByTagName('li'); // Line of concern
var array = [];
for(var i = 0; i < nodeList.length; i++) {
array[i] = nodeList[i];
}
for(var i = 0; i < array.length; i++) {
array[i].style.display = 'none';
}
Does not work (error is: "Uncaught TypeError: Cannot set property 'display' of undefined"):
var apple = document.getElementById('apple');
var nodeList = apple.parentNode.childNodes; // Line of concern
var array = [];
for(var i = 0; i < nodeList.length; i++) {
array[i] = nodeList[i];
}
for(var i = 0; i < array.length; i++) {
array[i].style.display = 'none';
}
So if both variables "nodeList" are actual node lists, then why can't I set the properties on the latter example, nor anything similar.
Also, how do I solve the issue on the latter?
No jQuery please for this question.
Thank you.
There are not two different types of NodeLists.
apple.parentNode.childNodes
returns a NodeList, but it contains ALL the nodes--including new line & space characters between elements on the HTML. So the reason I couldn't apply the properties I wanted was because some of the nodes were non-elements.
The answer then in place of that, is to use the element-only selecting methods; in this case: parentElement & children:
apple.parentElement.children
See Mozilla's Developer page on nodes, as well as the left-hand column for more node methods.

How to make array with string list

I have a generated list which is like this
196-1526, 85-651, 197-1519
I need the array like this. Each node has two part. I need only the first part of each node in one array.
196, 85, 197
I already have this code which generage 196
str.substr(0,str.indexOf('-'));
You could use the following:
'196-1526, 85-651, 197-1519'.replace(/-\d+(,|$)/g, '').split(/\s/)
If the input is a string you can use split() and push(), similar to this:
var x = "196-1526, 85-651, 197-1519"
var y = x.split(',');
var myArray = [];
for(i = 0; i < y.length; i++){
myArray.push(y[i].split('-')[0].trim());
}
DEMO - Using split() and push()
if it's an array
var myarray = ["196-1526", "85-651", "197-1519"];
var newarray = [];
var i = 0;
for(i = 0; i < myarray.length; i++){
var mnode = myarray[i].split("-");
newarray.push(mnode[0].trim());
}
and if it's a string
var myarray = "196-1526, 85-651, 197-1519".split(",");
var newarray = [];
var i = 0;
for(i = 0; i < myarray.length; i++){
var mnode = myarray[i].split("-");
newarray.push(mnode[0].trim());
}
Demo: http://jsfiddle.net/Dbbc8/
try this code using split
var text='196-1526, 85-651, 197-1519';
var splittedtext=text.split(',');
var numbers=new Array();
for(var i=0;i<splittedtext.length;i++)
{
var furthsplit=splittedtext[i].split('-');
numbers[i]=furthsplit[0];
}
alert(numbers);
var pairs = str.split(", ");
var values = [];
for (var i=0; i< pairs.length; i++) {
values.push(pairs[i].substr(0, pairs[i].indexOf('-')));
}

How to loop through Nested Json Array with (JavaScript) for loop and display the text

This may be a fairly simple question but it's just not working for me no matter how many times I change the for loop around. So how would you loop through this array using a for loop in JavaScript?
var fielditems =[
[["News Tips"],["Opinions"],["MedMinutes"]],
[["Yes"],["No"],["Maybe"]],
[["How"],["Why"],["When"]]
];
This is what I have and it's not working. I used an alert to just test out the result but it's not even returning anything.
for(itemSet in fielditems){
var itemSetValues = fielditems[itemSet];
for(set in itemSetValues){
var itemValue = itemSetValues[set];
for(value in itemvalue){
alert(itemValue[value]);
}
}
}
What am I doing wrong?
Don't use for() with in for arrays. It's for object properties. Use the standard format instead.
Demo: http://jsfiddle.net/ThinkingStiff/EVWch/
Script:
var fielditems =[
[["News Tips"],["Opinions"],["MedMinutes"]],
[["Yes"],["No"],["Maybe"]],
[["How"],["Why"],["When"]]
];
for( var itemIndex = 0; itemIndex < fielditems.length; itemIndex++ ){
var itemSetValues = fielditems[itemIndex];
for(var setIndex = 0; setIndex < itemSetValues.length; setIndex++ ){
var itemValue = itemSetValues[setIndex];
for(var valueIndex = 0; valueIndex < itemValue.length; valueIndex++ ){
alert(itemValue[valueIndex]);
};
};
};
​
Firstly, console is your friend. You get error ReferenceError: itemvalue is not defined because javascript is case sensitive. Change itemvalue in the most nested loop to itemValue.
Secondly, if you want iterate thorugh an array, you should use for-loop instead for-in-loop
Don't use for-in loops on arrays
Don't use (running) variables without declaring them as local
for (var i=0; i<fielditems.length; i++) {
var itemSetValues = fielditems[i];
for (var j=0; j<itemSetValues.length; j++) {
var itemvalue = itemSetValues[j]; // notice the case
for (var k=0; k<itemvalue.length; k++) {
alert(itemvalue[k]);
}
}
}
for..in is for objects ({}), not for arrays ([]).
You need to use a standard for loop.
for(var i = 0, iLen = fielditems.length; i < iLen; i++){
var iItem = fielditems[i];
for(var j = 0, jLen = iItem.length; j < jLen; j++){
var jItem = iItem[j];
alert(jItem[0]); // you can also add another loop here, if this will have more elements
}
}
NOTE:
for(var i = 0, iLen = fielditems.length; i < iLen; i++)
is better than:
for(var i = 0; i < fielditems.length; i++)
because fielditems.length isn't requested each loop, just once at the start.

Categories

Resources