I have this script that I would like to extend in order to be able to use dozens of lines...
var arr = [
{ name:'Susan', country:'USA', age:27 },
{ name:'John', country:'Canada', age:34 },
{ name:'Klaus', country:'Germany', age:23 },
{ name:'Peter', country:'Greece', age:29 }
];
var template = document.querySelector('#tmplt');
for (var i = 0; i < arr.length; i++) {
var user = arr[i];
var clone = template.content.cloneNode(true);
var h2 = clone.querySelectorAll('h2');
h2[0].className = "username";
h2[0].innerHTML = user.name;
var p = clone.querySelectorAll('p');
var div = clone.querySelectorAll('div');
div[0].className = "box";
p[0].className = "content";
p[0].innerHTML = "Country: "+user.country+"<br>Age: "+user.age;
template.parentNode.appendChild(clone);
}
Instead of putting all the users data in the script, I am trying to find a way to read them from a txt files. Can anyone help?
Instead of using a txt file it is better to use a json file like this:
users.json
[
{ name:'Susan', country:'USA', age:27 },
{ name:'John', country:'Canada', age:34 },
{ name:'Klaus', country:'Germany', age:23 },
{ name:'Peter', country:'Greece', age:29 }
]
if you are using node read the file like this:
var fs = require('fs');
var rawcontent = fs.readFileSync('./users.json','utf-8');
var users = JSON.parse(rawcontent)
console.log(users)
If you are running js on browser use fetch like this:
fetch('link to user.json')
.then(res=>res.json())
.then(data=>{
console.log(data)
})