現在要介紹的是:如何「動態的增加“html 標籤上的屬性”」
html:
1 | <h1 class="titleClass"> |

利用 JS「動態的變更href的值」
html:
1 | <h1 class="titleClass"> |
JS:
🎃 先建立變數el,選取「h1裡面的a連結」: var el = document.querySelector('.titleClass a');
🎃 用.setAttribute()來「設定屬性」
🍋 第一個單引號,寫:要變更哪個屬性
🍋 第二個單引號,寫:屬性的值
1 | var el = document.querySelector('.titleClass a'); |
🎃 點擊a連結,就會連到’https://www.tripadvisor.com.tw’了

動態新增id
html:
1 | <div class="str">hello</div> |
原本,.str是「黑色的文字」

🎃 我先在 css 新增一個 id 叫做「#strId」,並設定了新的「文字顏色、字體大小」
css:
1 | #strId{ |
現在,我要用 JS「動態新增id='strId'到.str上面」
JS:
1 | var el = document.querySelector('.str'); |
🎃 id='strId'就被新增到.str上面了,因此,就會套用#strId的 css 樣式

取出“屬性的值” .getAttribute()
html:
1 | <h1 class="titleClass"> |
JS:
1 | var el = document.querySelector('.titleClass a'); |
現在,我要做的是:
🎃 取出「a連結裡面,“href屬性的值”」
🍋 現在,“href屬性的值”已經被更改為 ‘https://www.tripadvisor.com.tw’
作法如下:
JS:
🎃 建立一個變數el2,來儲存「取出的“屬性值”」
🎃 用.getAttribute()來取出“屬性的值”
🍋 小括號裡面,寫:要取出哪個屬性
🎃 用console.log(el2);來看「取出的“屬性值”」
1 | var el = document.querySelector('.titleClass a'); |

取出“文字內容” .textContent
html:
1 | <h1 class="titleClass"> |
JS:
1 | var el = document.querySelector('.titleClass a'); |
現在,我要做的是:
🎃 取出「a連結裡面的“文字內容”」
作法如下:
JS:
🎃 建立一個變數el2,來儲存「取出的“文字內容”」
🎃 用.textContent來取出“文字內容”
🎃 用console.log(el2);來看「取出的“文字內容”」
1 | var el = document.querySelector('.titleClass a'); |

取出“html 標籤” .innerHTML
html:
1 | <h1 class="titleClass"> |
現在,我要做的是:
🎃 取出「.titleClass裡面的“html 標籤”」
(就是: <a href="https://www.tripadvisor.com.tw">title</a>)
作法如下:
