For context, currently working on an electron app that will help me learn Japanese.
I am wanting to add courses to a div
based on a list of JSON objects but what I have tried so far isn't working. How would I achieve my goal?
My Code:
index.html
<!DOCTYPE html>
<html >
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<link rel="stylesheet" href="./master.css">
<title>Nippon Ren</title>
</head>
<body>
<div >
<h1 id="app-title">Nippon Ren</h1>
<div >
<h2 >Continue</h2>
<div id="c" onl oad="loadCurrentCourses()">
<a href="./courses/add.html"><div id="courses-add">
</div></a>
</div>
</div>
<div >
<h2 >Revision</h2>
<div >
</div>
</div>
</div>
<!-- Page JS -->
<script src="./renderer.js"></script>
</body>
</html>
renderer.js
const fs = require('fs/promises')
const COURSES_CURRENT = document.getElementById("courses-current")
let coursesCurrent
const getCurrentCourses = async () => {
try {
await fs.access("./data/current_courses.json")
} catch {
coursesCurrent = { courses: [] }
}
if (!coursesCurrent) {
coursesCurrent = JSON.parse(await fs.readFile("./data/current_courses.json", "utf8"))
}
}
const loadCurrentCourses = async () => {
getCurrentCourses()
for (i in coursesCurrent["courses"]) {
let nextCourse = document.createElement("div")
nextCourse.className = "card"
document.getElementById("c").innerHTML = nextCourse
}
}
data/current_courses.json
{
"courses": [
{
"id": "0",
"title": "Getting Started with Hirigana",
"desc": "Intro"
}
]
}
The other method for adding the courses is:
...
const loadCurrentCourses = async () => {
getCurrentCourses()
for (i in coursesCurrent["courses"]) {
let nextCourse = document.createElement("div")
nextCourse.className = "card"
document.getElementById("c").appendChild(nextCourse)
}
}
...
CodePudding user response:
You are running JavaScript directly in the browser, but using require()
is only possible when running the code using NodeJS. If you want to use require()
, but run the code in a browser, try using Webpack.
Also, I don't see any element with id courses-current
in your HTML.
CodePudding user response:
You can use map function, something like this
const course = {
"courses": [
{
"id": "0",
"title": "Getting Started with Hirigana",
"desc": "Intro"
},
{
"id": "1",
"title": "Getting Started with Hirigana",
"desc": "Intro"
}
]
}
course.courses.map((currentElement) => {
console.log(currentElement); //append child here using the currentElement value
})