# 🏅 3/18 (四) 每日任務 ###### tags: `JS 直播班 - 2021 春季班` getAttribute, setAttribute 應用 ([參考章節](https://courses.hexschool.com/courses/1289881/lectures/30768828)) --- 以下連結為 HTML 的屬性列表,可以透過 getAttribute, setAttribute 操作這些屬性。 https://developer.mozilla.org/zh-TW/docs/Web/HTML/Attributes ### getAttribute #### 1. 使用 getAttribute 可以回傳一個元素上的指定屬性值,語法如下: ``` element.getAttribute("屬性名稱"); ``` **範例**: HTML ```htmlembedded= <div id="targetId">目標 Id</div> ``` JS ```js= let element = document.querySelector('#targetId'); console.log(element.getAttribute('id')); ``` 結果: ![](https://i.imgur.com/DvAMFov.png) #### 2. 使用 getAttribute 取用屬性時,如果指定的屬性不存在,則會回傳 `null` 或 `""`。 HTML ```htmlembedded= <div id="targetId">目標 Id</div> ``` JS ```js= let element = document.querySelector('#targetId'); console.log(element.getAttribute('name')); // 由於 name 屬性不存在,因此會回傳 null ``` 結果: ![](https://i.imgur.com/0bfxvG4.png) ### setAttribute #### 1. 可以使用 setAttribute 替指定元素設定屬性值,語法如下: ``` element.setAttribute("屬性名稱", "屬性值"); ``` 範例: HTML ```htmlembedded= <div id="targetId">目標 Id</div> ``` CSS ```css= .colorRed{ color: #FF0000; } ``` JS ```js= let element = document.querySelector('#targetId'); element.setAttribute('class', 'colorRed') ``` 結果 (以下為網頁渲染畫面): ![](https://i.imgur.com/F53xtGb.png) 問題 --- 請根據 HTML, CSS 以及題目條件撰寫 JS 程式碼 >如果 element 的 name 屬性為 "google",請執行以下要求: > >要求一: 將 element 的 href 屬性更改為 "https://www.google.com/" >要求二: 替 element 新增一個 target 屬性,並設定為 "_blank" >要求三: 替 element 新增一個 class 屬性,並設定為 "colorRed" HTML ```htmlembedded= <a href="#" id="targetId" name="google">google 連結</a> ``` CSS ```css= .colorRed{ color: #FF0000; } ``` JS ```js= let element = document.querySelector('#targetId'); if(/* 請填入程式碼 */){ /* 請填入程式碼 */ } ``` 回報流程 --- 將答案寫在 CodePen 並複製 CodePen 連結貼至 thread 中回報就算完成了喔! 解答請參考下圖(需打開程式碼的部分觀看) ![](https://i.imgur.com/6UoJVtD.png) <!-- 解答 let element = document.querySelector('#targetId'); if(element.getAttribute('name') === 'google'){ element.setAttribute('href', 'https://www.google.com/'); element.setAttribute('target', '_blank'); element.setAttribute('class', 'colorRed'); } -->