How to append an array to a div? - javascript

So I'm having some trouble getting my array to load into a specified area in my HTML, currently the HTML looks like this:
<body>
<div id="japan"></div>
</body>
<script src="Fisher-Yates.js"></script>
and my Javascript is:
let hiragana = [あ, い, う, え, お];
let result = shuffle(hiragana);
let div = document.getElementById('japan');
for (let i = 0; i < result.length; i++) {
div.appendChild(result[i]);
}
It will appear in the body if I replace the div.appendChild with document.body.appendChild instead, so I think some of the code should work, I'm just not sure what I'm missing!
EDIT: I should also mention that the array is variables that are images I'd like to load in at random, this is the rest of the code:
function shuffle(array) {
var m = array.length,
t,
i;
while (m) {
i = Math.floor(Math.random() * m--);
t = array[m];
array[m] = array[i];
array[i] = t;
}
return array;
}
let あ = document.createElement("img");
あ.src = "/images/あ.png";
//あ.setAttribute("width", "25%");
let い = document.createElement("img");
い.src = "/images/い.png";
let う = document.createElement("img");
う.src = "/images/う.png";
let え = document.createElement("img");
え.src = "/images/え.png";
let お = document.createElement("img");
お.src = "/images/お.png";

Try adding the image elements at the top of the code.
let あ = document.createElement("img");
あ.src = "/images/あ.png";
//あ.setAttribute("width", "25%");
let い = document.createElement("img");
い.src = "/images/い.png";
let う = document.createElement("img");
う.src = "/images/う.png";
let え = document.createElement("img");
え.src = "/images/え.png";
let お = document.createElement("img");
お.src = "/images/お.png";
let hiragana = [あ, い, う, え, お];
let result = shuffle(hiragana);
let div = document.getElementById('japan');
for (let i = 0; i < result.length; i++) {
div.appendChild(result[i]);
}
function shuffle(array) {
var m = array.length,
t,
i;
while (m) {
i = Math.floor(Math.random() * m--);
t = array[m];
array[m] = array[i];
array[i] = t;
}
return array;
}
<body>
<div id="japan"></div>
</body>
<script src="Fisher-Yates.js"></script>

Instead of div.appendChild(result[i]); Have you tried below code:
<body>
<div id="japan"></div>
</body>
<script src="Fisher-Yates.js"></script>
let hiragana = [あ, い, う, え, お];
let result = shuffle(hiragana);
div = document.getElementById('japan');
for (let i = 0; i < result.length; i++) {
div.innerHTML = div.innerHTML + result[i];
}

Related

Having issues creating a for loop for a list created in JS

I'm trying to for loop the H1 object through a list 10 times. I'm not sure where I went wrong any help would be appreciated.
var headOne = document.createElement("H1");
headOne.textContent = "Hello World";
document.body.appendChild(headOne);
var newOrderedList = document.createElement('OL');
newOrderedList.setAttribute("id", "OLJS");
document.body.appendChild(newOrderedList);
var helloWorld = document.getElementById("OLJS");
for (var i = 0; headOne < 10; i++){
var listItems = document.createElement("li");
listItems.innerHTML = headOne[i];
helloWorld.append(listItems);
}
If you want to loop 10 times then do:
for (let i = 0; i < 10; i++) {
// Do something
}
And in your case if you are trying to access each letter of headOne element and append it to the helloWorld list then you can do the following:
for (let i = 0; i < headOne.textContent.length; i++) {
let listItems = document.createElement('li')
listItems.textContent = headOne.textContent[i]
helloWorld.append(listItems)
}
You might also want to read more about Loops and iteration
var headOne = document.createElement("H1");
headOne.textContent = "Hello World";
document.body.appendChild(headOne);
var newOrderedList = document.createElement('OL');
newOrderedList.setAttribute("id", "OLJS");
document.body.appendChild(newOrderedList);
//var helloWorld = document.getElementById("OLJS");
for (var i = 0; i < 10; i++) {
var listItems = document.createElement("li");
listItems.innerHTML = "order list item " + (i + 1);
newOrderedList.append(listItems);
}

How to use for loop to sum a numbers inserted by the user?

i'm trying to create a simple project where the user is prompted to enter how many numbers he would like to add(sum). then when he click the button, a javascript will create a number of input tags equal to the number he inserted and then he will fill them with a number and click another button to calculate the result of the summation and here is the problem. below is a simplified snippet explain what is the problem:
function CL(){
const items = document.getElementById("items");
for (var i = 1; i < 3; i++) {
const inpt = document.createElement("input");
inpt.setAttribute("type","text");
inpt.setAttribute("style","margin:5px;");
inpt.setAttribute("id","y"+i);
inpt.setAttribute("value","");
const newline = document.createElement("br");
items.appendChild(inpt);
items.appendChild(newline);
}
}
function Add(){
const y = 0;
const sum = 0;
var is;
for (var i = 1; i < 3; i++) {
is = i.toString();
y = Number(document.getElementById('y'+ is).value);
sum = sum + y;
}
document.getElementById("demo").innerHTML = sum;
}
in the for loop how can i use getElementById with variables id like item1,item2,item3,...,itemN??
is there other way to achieve what i want?
You can take all items with ID "y" + consecutive number prefix on this way document.getElementById('y' + i).value;
Do not use "Add" for function name and Functions do not have to start with capital letters!
calckStart();
function calckStart() {
const items = document.getElementById("items");
for (var i = 1; i < 3; i++) {
const inpt = document.createElement("input");
inpt.setAttribute("type", "text");
inpt.setAttribute("style", "margin:5px;");
inpt.setAttribute("id", "y" + i);
inpt.setAttribute("value", "");
const newline = document.createElement("br");
items.appendChild(inpt);
items.appendChild(newline);
}
var button = document.createElement('button');
button.innerHTML = 'ClickMe'
items.appendChild(button);
button.addEventListener('click', calculateVal);
}
function calculateVal() {
var res = 0;
for (var i = 1; i < 3; i++) {
res = res + +document.getElementById('y' + i).value;
}
var items = document.getElementById("items");
var result = document.createElement('div');
result.innerHTML = res;
items.appendChild(result);
}
<div id="items"></div>
A better way is ...
When you create elements, you can assign them a CLASS attribute that is one for all input elements. You can then take the values from all elements with this class.
Example:
calckStart();
function calckStart() {
const items = document.getElementById("items");
for (var i = 1; i < 3; i++) {
const inpt = document.createElement("input");
inpt.setAttribute("type", "text");
inpt.setAttribute("style", "margin:5px;");
// inpt.setAttribute("id", "y" + i);
inpt.setAttribute("value", "");
inpt.setAttribute("class", "numbers"); //<-- Set class
const newline = document.createElement("br");
items.appendChild(inpt);
items.appendChild(newline);
}
var button = document.createElement('button');
button.innerHTML = 'ClickMe'
items.appendChild(button);
button.addEventListener('click', calculateVal);
}
function calculateVal() {
var list = document.getElementsByClassName('numbers'); //<-- Get by class
var res = 0;
for (var i = 0; i < list.length; i++) {
res = res + +list[i].value;
}
var items = document.getElementById("items");
var result = document.createElement('div');
result.innerHTML = res;
items.appendChild(result);
}
<div id="items"></div>
You can use ...args to collect arguments and use .reduce to add the arguments together.
const items = document.getElementById("items");
for (var i = 0; i < 3; i++) {
var inpt = document.createElement("input");
inpt.setAttribute("type","number"); //replaced with number
inpt.setAttribute("style","margin:5px;");
inpt.setAttribute("id","y"+i);
inpt.setAttribute("value","");
var newline = document.createElement("br");
items.appendChild(inpt);
items.appendChild(newline); //added newline appending
}
function sum(...args) {
return args.reduce((a, b) => a+b); //reduce arguments
}
<div id="items"></div><br /><button onclick="document.getElementById('answer').textContent = 'answer: ' + sum(+y0.value, +y1.value, +y2.value)">Add</button><div id="answer"></div>

Create div Using Array

I have an array of strings, I want to show each array element in its own <div> tag like
<div "class">one</div><div class"two">one</div> and each div tag should have a class that is common for all. All process start on click button
BUTTON CODE
<asp:Button OnClientClick="abc();" runat="server" />
JAVASCRIPT FUNCTION
function abc()
{
debugger;
var arrayVariable = "one,two,three";
var arrayLength = arrayVariable.length;
var temp;
for (i = 0; i < arrayLength; i++) {
temp = document.createElement('div');
temp.className = 'results';
temp.innerHTML = arrayVariable[i];
$('#inputcomshow').append(temp);
//document.getElementById("#inputcomshow").value = replaced
}
}
You need to convert string into array first.
Use this:
function abc()
{
debugger;
var stringVariable = "one,two,three"; // string
var arrayVariable = stringVariable.split(","); // now string to array
var arrayLength = arrayVariable.length;
var temp;
for (i = 0; i < arrayLength; i++) {
temp = document.createElement('div');
temp.className = 'results';
temp.innerHTML = arrayVariable[i];
$('#inputcomshow').append(temp);
//document.getElementById("#inputcomshow").value = replaced
}
return false;
}
Use This
<asp:Button OnClientClick=" javascript:return abc();" runat="server" />
<script>
function abc() {
debugger;
var stringVariable = "one,two,three"; // string
var arrayVariable = stringVariable.split(","); // now string to array
var arrayLength = arrayVariable.length;
var temp;
for (i = 0; i < arrayLength; i++) {
temp = document.createElement('div');
temp.className = 'results';
temp.innerHTML = arrayVariable[i];
$('#inputcomshow').append(temp);
//document.getElementById("#inputcomshow").value = replaced
}
return false;
}
</script>
Try it with less number variable and pure javascript, because you only used single line jQuery code $('#inputcomshow').append(temp);.
function abc(){
var arrayVariable = "one,two,three";
arrayVariable = arrayVariable.split(',');
for (i = 0; i < arrayVariable.length; i++) {
temp = document.createElement('div');
temp.className = 'results';
temp.innerHTML = arrayVariable[i];
document.getElementById("inputcomshow").appendChild(temp);
}
}

appendchild is not working

I am working on nested array. When i am trying to insert data to a div by using appendChild It is throwing an error saying Cannot read property 'appendChild' of null
My Code goes hear
<script>
var emp1 = [];
emp1["Emsno"] = 10001;
emp1["name"] = "jack";
emp1 ["sall"] = 5000;
var emp2 = [];
emp2["Emsno"] = 10002;
emp2["name"] = "Reck";
emp2 ["sall"] = 5500;
var emp3 = [];
emp3["Emsno"] = 10003;
emp3["name"] = "lama";
emp3 ["sall"] = 5300;
var emp4 = [];
emp4["Emsno"] = 10004;
emp4["name"] = "sam";
emp4 ["sall"] = 6000;
var emps = [emp1, emp2, emp3, emp4];
var Employedisplay = document.getElementById("Employedisplay");
function showEmployes(){
var n = emps.length;
for (i = 0; i < n ; i++){
var emp = emps[i];
for(var key in emp){
var NewDiv = document.createElement("div");
NewDiv.innerHTML = key + ": " + emp[key];
Employedisplay.appendChild(NewDiv);
}
var NewBrk = document.createElement("br")
Employedisplay.appendChild(NewBrk);
}
}
</script>
</head>
<body>
<input type = "button" id = "MyArray" value ="Show Emps" onclick="showEmployes()"/>
<hr>
<div id="Employedisplay"></div>
</body>
and it is working in this way
function showEmployes(){
var n = emps.length;
for (i = 0; i < n ; i++){
var emp = emps[i];
for(var key in emp){
var NewDiv = document.createElement("div");
NewDiv.innerHTML = key + ": " + emp[key];
document.getElementById("Employedisplay").appendChild(NewDiv);
}
var NewBrk = document.createElement("br")
Employedisplay.appendChild(NewBrk);
}
}
I am not understanding where i am going wrong in my first approach?
The below line of code is executed even before the browser add the #Employedisplay element in DOM.
var Employedisplay = document.getElementById("Employedisplay");
So when you click the button, Employedisplay variable is null
It's better to bootstrap your code on page load, or you can get the #Employedisplay element at the start of showEmployee method.
<script>
var emp1 = [];
emp1["Emsno"] = 10001;
emp1["name"] = "jack";
emp1["sall"] = 5000;
var emp2 = [];
emp2["Emsno"] = 10002;
emp2["name"] = "Reck";
emp2["sall"] = 5500;
var emp3 = [];
emp3["Emsno"] = 10003;
emp3["name"] = "lama";
emp3["sall"] = 5300;
var emp4 = [];
emp4["Emsno"] = 10004;
emp4["name"] = "sam";
emp4["sall"] = 6000;
var emps = [emp1, emp2, emp3, emp4];
function bootstrap() {
var Employedisplay = document.getElementById("Employedisplay");
}
function showEmployes() {
var n = emps.length;
for (i = 0; i < n; i++) {
var emp = emps[i];
for (var key in emp) {
var NewDiv = document.createElement("div");
NewDiv.innerHTML = key + ": " + emp[key];
Employedisplay.appendChild(NewDiv);
}
var NewBrk = document.createElement("br")
Employedisplay.appendChild(NewBrk);
}
}
</script>
</head>
<body onload="bootstrap();">
<input type="button" id="MyArray" value="Show Emps" onclick="showEmployes()" />
<hr>
<div id="Employedisplay"></div>
</body>
<script>
var emp1 = [];
emp1["Emsno"] = 10001;
emp1["name"] = "jack";
emp1 ["sall"] = 5000;
var emp2 = [];
emp2["Emsno"] = 10002;
emp2["name"] = "Reck";
emp2 ["sall"] = 5500;
var emp3 = [];
emp3["Emsno"] = 10003;
emp3["name"] = "lama";
emp3 ["sall"] = 5300;
var emp4 = [];
emp4["Emsno"] = 10004;
emp4["name"] = "sam";
emp4 ["sall"] = 6000;
var emps = [emp1, emp2, emp3, emp4];
function showEmployes(){
var Employedisplay = document.getElementById("Employedisplay");
var n = emps.length;
for (i = 0; i < n ; i++){
var emp = emps[i];
for(var key in emp){
var NewDiv = document.createElement("div");
NewDiv.innerHTML = key + ": " + emp[key];
Employedisplay.appendChild(NewDiv);
}
var NewBrk = document.createElement("br")
Employedisplay.appendChild(NewBrk);
}
}
</script>
</head>
<body>
<input type = "button" id = "MyArray" value ="Show Emps" onclick="showEmployes()"/>
<hr>
<div id="Employedisplay"></div>
</body>

Randomly shuffle innerHTML

I'm trying to shuffle som innerHTML, I've created some divisions were I add content from a list, now I want to shuffle this everytime I load the site. I've come up with this solution, and it shuffles the innerHTML, but It doesn't put it out in new HTML. Any ideas how to tweak it? Later I will create and shuffle a list of hrefs of image pictures. So basically it is going to be an 9-square image randomizer. I would really appriciate some help :)
<script>
var squareNumbers = ['1','2','3','4','5','6','7','8','9']; //need to create a new list to append image hrefs
for(var i = 0; i<=squareNumbers.length-1; i++){ //creates the chessboard
var div = document.createElement('div');
div.setAttribute('id', 'square'+squareNumbers[i]);
div.innerHTML = squareNumbers[i];
var checkHTML = document.getElementById('chessBoard').appendChild(div);
}
window.onload = function(){
var squareDivs = document.getElementById('chessBoard').getElementsByTagName('div');
var array = [];
for(var i = 0; i < squareDivs.length; i++){ //creates an array of the squares innerHTML
array.push(squareDivs[i].innerHTML);
}
var i = array.length, j, temp;
while(--i > 0){ //shuffles the array according to Fisher Yeates algorithm
j = Math.floor(Math.random() * (i+1));
temp = array[j];
array[j] = array[i];
array[i] = temp;
var squares = document.getElementById('chessBoard').getElementsByTagName('div').innerHTML = temp;
console.log(squares);
}
}
</script>
Update
This just updates them.
var squareNumbers = ['1','2','3','4','5','6','7','8','9'], j, temp;
for(var i = 0; i < squareNumbers.length; i++){ //creates the chessboard
var div = document.createElement('div');
div.setAttribute('id', 'square' + squareNumbers[i]);
div.innerHTML = squareNumbers[i];
document.getElementById('chessBoard').appendChild(div);
}
window.onload = function(){
for (i = squareNumbers.length - 1; i >= 0; i--) {
j = Math.floor(Math.random() * (i + 1));
temp = squareNumbers[j];
squareNumbers[j] = squareNumbers[i];
squareNumbers[i] = temp;
document.getElementById('chessBoard').getElementsByTagName('div')[i].innerHTML = temp;
}
}
Previous
Here, this does that:
window.onload = function(){
var squareNumbers = ['1','2','3','4','5','6','7','8','9'], j, temp;
for (i = squareNumbers.length - 1; i >= 0; i--) {
j = Math.floor(Math.random() * (i + 1));
temp = squareNumbers[j];
squareNumbers[j] = squareNumbers[i];
squareNumbers[i] = temp;
var div = document.createElement('div');
div.setAttribute('id', 'square'+squareNumbers[i]);
div.innerHTML = squareNumbers[i];
document.getElementById('chessBoard').appendChild(div);
}
}

Categories

Resources