---
# System prepended metadata

title: 第五堂：期中試煉
tags: [JS 直播班 - 2022 秋季班]

---

---
tags: JS 直播班 - 2022 秋季班
---





## DOM(文件物件模型)
* 取 DOM： `document.querySelector("CSS選擇器")`
* DOM 內新增文字節點：`document.querySelector("CSS選擇器").textContent = "hello world"`;
* DOM 內新增 HTML：`document.querySelector("CSS選擇器").innerHTML = "<h2>新增標題</h2>"`;
* [程式碼範例](https://codepen.io/hexschool/pen/wvoRboe?editors=1010)

![](https://i.imgur.com/mFFO0hR.jpg)

> textContent 是否能穿插 HTML tag？


## forEach 語法教學
* 為什麼要學 [forEach](https://www.hexschool.com/2017/09/01/2017-09-01-javascript-for/)？`[2,3,5] 裡面的文字你會如何加總？`
### forEach 語法講解
```javascript=
let data = [3,30,100]
data.forEach(function(item,index,ary){
    console.log(item,index,ary)
})
```
### forEach 陣列數字累加
```javascript=
let data = [3,30,100];
let total=0;
data.forEach(function(item,index,ary){
    total+=item;
})
```

### forEach 物件裡面的數字累加
```javascript=
let data = [
  {
    num: 10
  },
  {
    num: 30
  },
  {
    num: 100
  }
];
let total = 0;
data.forEach(function(item, array, ary){
  total+=item.num;
})
```

### forEach + innerHTML
* [範例零](https://codepen.io/hexschool/pen/wvoRboe?editors=1010)
* [範例一：字串累加](https://codepen.io/hexschool/pen/WNoLBjd?editors=1010)
* [範例二](https://codepen.io/hexschool/pen/GRNParj?editors=1010)
* 以[第五關主線任務](https://github.com/hexschool/js-training/blob/main/travelApi.json)為例、[CSS 現成模版](https://codepen.io/hexschool/pen/poNqmEL)





## forEach + if

* [男生共有幾位？](https://codepen.io/hexschool/pen/yLVGWpx?editors=1010)
* [國中學校人數](https://data.tainan.gov.tw/dataset/junior-number/resource/4f56ba22-0b13-4570-8be6-2d66483ffa5f)
<!--     * [練習](https://codepen.io/liao/pen/OJjzPWe?editors=0010) -->
* [高雄里長資訊](https://cabu4.kcg.gov.tw/KcgRegion/OpenData/%E9%87%8C%E9%95%B7%E9%80%9A%E8%A8%8A%E9%8C%84.JSON)
<!--     * [練習](https://codepen.io/liao/pen/XWaVJaa?editors=0010) -->
