I am trying to create multiple divs and assign them a unique ID with javascript, preferably the name of a state as it's printed in the console log. Nothing I try works though. Any advice? I have followed every similar question and answer I can find on this forum but nothing works for my situation.
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
<body>
<div id="myDiv">
</div>
<script>
getData(); //call function
async function getData(){ //define an asynchronous function
var response = await fetch('covid.csv'); //call data and assign it to a variable
var data = await response.text(); //parse the text from the response and assign it to variable
console.log(data);
var table = data.split('\n').slice(1, -1); //delineate rows of the table by splitting them at the line break. This results in an array such as: [0] Alaska, 12, 1.33 etc
console.log(table);
table.forEach(row => {
var columns = row.split(',');
var state = columns[0];
var deaths = columns[1];
var deathsPer = columns[2];
console.log(state, deaths, deathsPer);
/*
document.getElementById("myDiv").innerHTML = //DOESN'T WORK need to create new div for each row
state +
" death toll is " +
deaths +
" and a death rate of " +
deathsPer
;
*/
for(var i=0;i<50;i++){ //DOESN'T WORK creates 50 divs x50
var newDiv = document.createElement("div");
document.body.appendChild(newDiv);
newDiv.setAttribute("id", 'textBar' + i);
}
});
}
</script>
</body>
</html>
You are already looping with your forEach
, so no need for the extra loop. And inside that extra loop, you were not setting the innerHML:
ES6 version
const $myDiv = document.getElementById('myDiv');
(async function getData() {
// Just for the demo
const data = '\nVirginia,12,1\nCalifornia,24,3\nFlorida,36,11\n';
const table = data.split('\n').slice(1, -1);
table.forEach(row => {
const [ state, deaths, deathsPer ] = row.split(','),
$newDiv = document.createElement("div");
$newDiv.innerHTML = `${state} death toll is ${deaths}
and a death rate of ${deathsPer}`;
$newDiv.id = `textBar_${state}`;
$myDiv.appendChild($newDiv);
});
})();
<div id="myDiv"></div>
An easier to understand version (only with the ES6 features you were already using)
const $myDiv = document.getElementById('myDiv');
getData();
async function getData() {
// Just for the demo
const data = '\nVirginia,12,1\nCalifornia,24,3\nFlorida,36,11\n',
table = data.split('\n').slice(1, -1);
table.forEach(row => {
const columns = row.split(','),
state = columns[0],
deaths = columns[1],
deathsPer = columns[2],
$newDiv = document.createElement("div");
$newDiv.innerHTML = state + " death toll is " + deaths
+ " and a death rate of " + deathsPer;
$newDiv.id = "textBar_" + state;
$myDiv.appendChild($newDiv);
});
}
<div id="myDiv"></div>