Append to an array made from ul [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 8 years ago.
Improve this question
Hi im trying to append a "s" to each element an array created from a unsorted list. Here is my code and I am not sure what I am doing wrong.
Html:
<ul>
<li class="fruit">Apple</li>
<li class="fruit">Banana</li>
<li class="fruit">Pineapple</li>
<li class="fruit">Orange</li>
</ul>
Javascript to append s to each element
var list = document.getElementByClassName('friut');
for(var i=0;i < list.length; i++) {
var arrValue = list[i];
list[i] = arrValue.innerHTML + 's';
}

First, you misspelled both getElementsByClassName and "fruit". If all you are trying to do is make an array of strings equal to the list elements' values + "s", that's your problem.
If you're trying to actually add 's's to the HTML, you want something like this:
for(var i=0;i < list.length; i++) {
list[i].innerHTML += 's';
}

It's getElementsbyClassName, not getElementByClassName. You also spelled 'fruit' as 'friut'
var list = document.getElementsByClassName('fruit');
for(var i=0;i < list.length; i++) {
var arrValue = list[i];
list[i] = arrValue.innerHTML + 's';
}

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

How can I print a js array into a div in html? [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
Why I cant display elements that I push into an array, into an html div. Im just trying to print the word hello 3 times, but it does not work. When I print the array into the console the array does show the 3 Hello's.
$(function() {
var $buttonsArray = [];
var $buttondiv = $('#btndiv');
for (var i = 0; i < 3; i++) {
var $button = "hello";
$buttonsArray.push($button);
}
for (var j = 0; j < $buttonsArray.length; j++) {
$buttondiv.append($buttonsArray[j]);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="btndiv"></div>
HTML is mainly text (or call it a string) and javascript variables can be string, number, objects, arrays.
By default, on all those javascript types, if you just place them into a DOM elements, the browser will attempt to convert them to string.
const someNumber = 1
const someString = 'hello'
const someObject = {answer:42}
const someArray = [1, 'help', 3, {a:2}]
document.write(someNumber + '<br/ >')
document.write(someString + '<br/ >')
document.write(someObject + '<br/ >')
document.write(someArray + '<br/ >')
// is the same as
document.write(someNumber.toString() + '<br/ >')
document.write(someString.toString() + '<br/ >')
document.write(someObject.toString() + '<br/ >')
document.write(someArray.toString() + '<br/ >')
When you deal with an array, you can use .join to regroup them
for example
const greets = ['allo', 'hello', 'holla'];
function render() {
// This write the list separated with comas using join
document.getElementById('app').innerHTML = greets.join(', ');
// This works too but can be slow and doesn't not allow much flexibility
document.getElementById('debug').innerHTML = JSON.stringify(greets);
}
render();
setTimeout(() => {
greets.push('oi');
render();
}, 1000)
<div id="app"></div>
<pre id="debug"></pre>

Unexpected behaviour with for in a nodelist [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 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.

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.

Categories