Unexpected behaviour with for in a nodelist [closed] - javascript

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I have a nodelist with 30 divs and I need to include 1 div every 4 divs but the var 'c' does not change and stack all the divs in the position[6].
for (i = 0; i < 8; i++) {
var pub = "pub-retangulo-";
var c = 2;
c += 4;
var o = document.createElement("div");
o.setAttribute("id", pub.concat(i.toString()));
o.setAttribute("align", "center");
var container = document.querySelectorAll(".short-summary")[c];
container.parentNode.insertBefore(o, container);
}

You are redeclaring your c variable at each iteration. That is why is it stuck at 6. You need to move this assignation outside your loop
var pub = "pub-retangulo-";
var c = 2;
for (i = 0; i < 8; i++) {
var o = document.createElement("div");
o.setAttribute("id", pub.concat(i.toString()));
o.setAttribute("align", "center");
var container = document.querySelectorAll(".short-summary")[c];
container.parentNode.insertBefore(o, container);
c += 4;
}
I've also moved your c+=4 at the end of the loop, this will cause the loop to execute at c = 2 the first time rather than c = 6
As Barmar said, you might not need a variable at all in this case. You are incrementing by four each time, so you could replace your c variable with 2 (initial value) + i(current iteration index) * 4 (increment ratio).
P.S. This code is UNTESTED, please don't just copy and paste it expecting everything to work perfectly. Try to understand it and apply it to your own context.

Related

tried reverse array but reverse last item instead [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I tried to reverse array items, but it reverse the last item not array. I also posted the expected output. Hope it will make easy to understand.
var color = ("red", "green", "blue");
function printReverse(str) {
for (var i = str.length - 1; i >= 0; i--) {
console.log(str[i]);
}
}
printReverse(color);
/*
output
e
u
l
b
*/
You define arrays with this statement: ["red","green","blue"], not this: ("red","green","blue"):
var color = ["red","green","blue"];
function printReverse(str){
for ( var i = str.length-1; i>= 0; i-- ){
console.log(str[i]);
}
}
printReverse(color);
var color = ["red","green","blue"];
var rev_color = color.reverse()

Javascript function causing error not defined [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I have a simple function that seems to be causing an 'Uncaught ReferenceError: arraySort is not defined' whenever the function is called, in this case by a button and i cant see why any help would be brilliant.
Javascript
<script language="javascript">
var unsorted = ["Printer","Tablet","Router"];
var alphaOrder = [" ","A","a","B","b","C","c","D","d","E","e","F","f","G","g", //15
"H","h","I","i","J","j","K","k","L","l","M","m","N","n","O", //30
"o","P","p","Q","q","R","r","S","s","T","t","U","u","V","v", //45
"W","w","X","x","Y","y","Z","z","0","1","2","3","4","5","6", //60
"7","8","9","'","?","!",".","\"","<",">","#",",","#","~","=", //75
"+","-","_","/","\\"];
function arraySort(array){
var sortedArray = [];
var letterNum = 0;
var numArray = [];
function letterToNum(){
for (var elementNum = 0; elementNum < array.length; elementNum++;){
for (var alphaNum = 0; alphaNum < alphaOrder.length; alphaNum++;){
numArray[elementNum] = alphaOrder.indexOf(array[elementNum][letterNum]);
document.getElementById('tester1').innerHTML = numArray;
}
}
}
}
</script>
HTML
<button type = "button" onclick = "arraySort(unsorted)">Sort</button>
Remove the semicolon from the end of your loops.
for (var elementNum = 0; elementNum < array.length; elementNum++) {
for (var alphaNum = 0; alphaNum < alphaOrder.length; alphaNum++) {
}
Few suggestions here
Wrap your logic inside script by window.onload
Don't mix your markup and javascript.
Try binding events at javascript end
Follow the above suggestions, your error will be fixed.

Having trouble with getElementsByTagName(blockquote) [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I am trying to get it to return "ha, awesome" followed by the index of the word "awesome"
HTML:
<blockquote id = "blocky">
ha, awesome<br>
</blockquote>
JS:
var x = document.getElementsByTagName(blockquote).innerHTML ;
var n = x.indexOf("awesome");
document.getElementsByTagName(blockquote).innerHTML = x + "<br>" + n;
If I change the JS to this, it works
var x = document.getElementById("blocky").innerHTML ;
var n = x.indexOf("awesome");
document.getElementById("blocky").innerHTML = x + "<br>" + n;
https://jsfiddle.net/mzrt/zaf98g8y/1/
First off, you need to pass it a string, not a variable (unless that variable contains a string).
var x = document.getElementsByTagName('blockquote');
Next, document.getElementsByTagName returns a element collection, not a single element. You can get the first result using [0].
var x = document.getElementsByTagName('blockquote')[0];
Or you can iterate through all of the elements using a for loop.
for (var i = 0; i < x.length; i++) {
var element = x[i];
element.innerHTML = '...';
}
Basically getElementsByTagName will return a node list, an array like object, you cannot access the property of a node from it directly, you have to use bracket notation to fetch the first node from it and then you can treat it as a node object,
var x = document.getElementsByTagName('blockquote')[0].innerHTML;
Since the element that you are targeting is an element with id, It is better to go with getElementById.
var x = document.getElementsByTagName('blockquote')[0].innerHTML ;
var n = x.indexOf("awesome");
document.getElementsByTagName('blockquote')[0].innerHTML = x + "<br>" + n;
Get element by tag name returns a node list, so you have to tell whitch node you do want.
Also you should pass tagname between single quotes.

How do I use repeated value in innerhtml? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I used this code but it's not repeat
it increase the value but don't get to the initial value 0
please help
i=0;
function loading()
{
text=["Loading.","Loading..","Loading...","Loading...."];
window.setInterval(wr(),500)
}
function wr()
{
if(i<4)
{
wr='document.getElementById("text").innerHTML=text[i]';
alert(i);
}
else
i=0;
return wr;
}
Your code is way to complicated. Define a simple function which you pass to setInterval and make sure you increase the counter variable:
var i = 0; // initialize counter
var textElement = document.getElementById("text");
setInterval(function() {
i = i % 4; // make sure `i` is at max 3 and reset to 0
var text = 'Loading';
for (var j = i; j--; ) {
text += '.'; // add the correct number of periods
}
textElement.innerHTML = text; // set text
i++; // increase counter
}, 500);
DEMO
Here's a slight modification of a similar answer I gave a while back.
var i = 0;
setInterval(function() {
i = ++i % 4;
document.getElementById('text').innerHTML = "Loading"+Array(i+1).join(".");
}, 500);

Can i make my code shorter? [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 9 years ago.
Improve this question
I have many functions for calculating some stats , and i need to recheck the value's every time but that is extra code and make's it harder to read , can i store the variable assignment in another function:
function MC () {
var check=document.getElementById('check').checked;
var ea=Number(document.form.ea.value),
ed=Number(document.form.ed.value),
pa=Number(document.form.pa.value),
pd=Number(document.form.pd.value);
var hpSum = 0,spSum=0,eaSum=0,edSum=0,pdSum=0,paSum=0;
if(check){
eaSum = ea + 11;
edSum = ed + 17;
pdSum = pd + 17;
paSum = pa + 11;
} else {
eaSum = ea - 11;
edSum = ed - 17;
pdSum = pd - 17;
paSum = pa - 11;
}
document.form.ea.value=eaSum;
document.form.ed.value=edSum;
document.form.pa.value=paSum;
document.form.pd.value=pdSum;
};
NOTE:I am speaking for the variables:ea,ed,pa,pd and sum variables.
You could try building an object of parameters:
function MC() {
var check = document.getElementById('check').checked,
keys = {
"ea":11,
"ed":17,
"pd":17,
"pa":11
}, i;
for( i in keys) { if( keys.hasOwnProperty(i)) {
document.form[i].value = +document.form[i].value + (check ? keys[i] : -keys[i]);
}}
}
Note that +somevar is a cheap shortcut for parseFloat(somevar). Number(somevar) is NOT the same as it creates a wrapper object that may interfere with comparisons if you add any in later.
I'd go with your own code, condensed a bit. Assuming form is the name of a form, it would take more code to keep track which inputs have changed than to read them.
function MC () {
var f= document.form,
v= document.getElementById('check').checked? [11, 17]:[-11, -17];
f.ea.value= Number(f.ea.value)+v[0];
f.ed.value= Number(f.ed.value)+v[1];
f.pa.value= Number(f.pa.value)+v[0];
f.pd.value= Number(f.pd.value)+v[1];
}

Categories