# JSON SERVER and the DOM
- How the DOM works as tree
- Finding Html Elements
- Creating and Connecting to json-server
- Node single point in the DOM
## resources
### Html Template `index.html`
```html=
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>student tracker</title>
<link rel="stylesheet" href="index.css">
<link rel="author" href="humans.txt">
</head>
<body>
<section class="main">
<div class="sidebar">
<ul id="student-list">
</ul>
</div>
<div class="body-text">
<h1> Grade:<span id='grade'></span></h1>
<ul class="subjects">
<li >Maths: <span id="maths"></span></li>
<li > Chemistry:<span id="chemistry"></span></li>
<li >Physics: <span id="physics"></span> </li>
</ul>
</div>
</section>
<script type="text/javascript" src="index.js"></script>
</body>
</html>
```
### mock css `index.css`
```css=
.sidebar {
height: 100%;
width: 200px;
position: absolute;
left: 0;
top: 0;
padding-top: 40px;
background: rgb(5, 68, 104);
}
.sidebar ul li {
display: block;
padding: 13px 30px;
color: #fff;
font-size: 30px;
position: relative;
}
.body-text {
margin-top: 50px;
margin-left: auto;
margin-right: auto;
width: 50em
}
h1, .grade {
font-size: 60px;
}
.subjects {
font-size: 30px;
}
```
### JS Update `index.js`
```javascript=
// store data from API
let students = []
const url = 'http://localhost:3000/students'
let unorderdList = document.getElementById('student-list')
async function fetchStudents(){
try {
let res = await fetch(url)
let json = await res.json()
students = json
}catch (e) {
console.error(e)
}
}
const template = (name, id) => `<li class='student' id=${id}>${name}</li>`
async function renderStudents(){
let html = students.map(({name, id}) => template(name,id))
unorderdList.innerHTML = html.join(`\n`)
updateStudentData(students[0])
const allStudentsList = document.querySelectorAll('.student')
allStudentsList.forEach((node) => {
node.style.cursor = 'pointer'
node.addEventListener('click', (e) => {
let clickedObj = students.find((ele) => ele.id === parseInt(node.id))
// updater function
updateStudentData(clickedObj)
})
})
}
async function updateStudentData(obj){
const {grade, marks: {chemistry, maths, physics}} = obj
document.getElementById('grade').innerHTML = grade
document.getElementById('maths').innerHTML = maths
document.getElementById('physics').innerHTML = physics
document.getElementById('chemistry').innerHTML = chemistry
}
document.addEventListener('DOMContentLoaded', async (e) => {
await fetchStudents()
await renderStudents()
})
```
### mock json-server `db.json`
```json=
{
"students":[
{
"id":1,
"name":"alex",
"grade":11,
"marks":{
"maths":80,
"physics":60,
"chemistry":35
}
},
{
"id":2,
"name":"gary",
"grade":12,
"marks":{
"maths":70,
"physics":50,
"chemistry":65
}
},
{
"id":3,
"name":"stuart",
"grade":8,
"marks":{
"maths":75,
"physics":20,
"chemistry":90
}
}
]
}
```