# 3. setAttribute - 增加標籤屬性 ### 透過 JavaScript 動態的方式-設定 / 新增屬性給「標籤」: - 假設來講,我們 HTML 目前有下列的內容: ``` <h1 class="titleClass"> <a href="#">title</a> </h1> ``` - 接下來要做的事就是,透過 JS 來修改裡面的屬性: 1. 宣告一個變數名稱,且指定到 .titleClass 的 a 連結 2. 透過 setAttribute 指定 el 變數來修改屬性 ``` // JavaScript: var el = document.querySelector('.titleClass a'); el.setAttribute('href', 'https://www.cpbl.com.tw/'); // '欲更改的屬性' , '值=這邊因為是改 href 所以值自然也就是網址' ``` 3. 如此一來,第一個 setAttribute 屬性設定就完成了! --- ### 透過撈取屬性的方式,來變更樣式: - 新增一組類別標籤內容: ``` <div class="str">hello</div> ``` 1. 重新整理畫面之後,自然會得到一個黑色文字 hello。 2. 假使來講,我們有一個本身已經寫好的 CSS 內容如下: ``` // CSS: 文字藍色、字型大小: 50px #strId { color: blue; font-size: 50px; } ``` 3. 透過 setAttribute 指定 el2 變數來修改屬性: ``` 1. 宣告 el2 且指定 .str class // var el2 = document.querySelector('.str'); 2. el2 設定 setAttribute,設定 id 為 css 內的 #strId el2.setAttribute('id', 'strId'); ``` 4. 是的,原本平凡無奇的黑色文字就變成了: 藍色、50px  --- ###### tags: `JavaScript - DOM 元素`
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up