比較 getAttribute 與 setAttribute 的不同
由於 getAttribute、setAttribute 這兩種 JavaScript 語法看起來很相似,在初學 JS 的時候,真的很容易搞混,因此這篇筆記的主題是要來比較這兩種語法的功能。
透過 getAttribute、setAttribute 皆可操作 HTML 屬性,但兩者差異在於, getAttribute 是透過選取元素上的屬性名稱,就能得到該選取元素屬性的值,既然是回傳一個值,因此 getAttribute 其實就是可以用來取值和組資料的!(關於 setAttribute 取值的部分會再和 dataset 另文討論)
getAttribute 怎麼用?
寫法如下:
element.getAttribute("屬性名稱");
來看看範例吧!
假如今天我想要透過 JS 取得一個 id 上的值,搭配 dataset,可以這樣做:
//HTML
<div id="this-year" data-year="2021">今年是2021年</div>//JS
let element = document.querySelector('#this-year-2021'); console.log(element.getAttribute('id'));於是,根據這樣的設計:// element.getAttribute('id') 印出的結果會是 'this-year'
// element.getAttribute('data-year') 印出的結果會是 '2021'所以還可以透過 getAttribute 組一個資料,並渲染在畫面上let str = `${element.getAttribute('id')} is ${element.getAttribute('data-year')}`element.textContent = str;
以上就是 getAttribute 取值的用法,另外要特別注意的是,假如 getAttribute 要選取的屬性不存在,就會回傳 null
或 ""
。
那麼,說明完 getAttribute 後,再來看一看,setAttribute 的用法吧。
簡單來說,setAttribute 是可以同時用來增設 HTML 元素上的屬性以及屬性的值,因此如果搭配 CSS,就可以透過 setAttribute 來更改 HTML 元素的樣式!
setAttribute 怎麼用?
寫法如下:
element.setAttribute("屬性名稱", "屬性值");
一樣來看看範例吧!
//HTML
<div id="title-text">title text</div>//JS
let element = document.querySelector('#title-text');
由於 title text 只是由一般的 div 包裹著,它的文字要當成 title 實在太小了,如果我不更動 HTML,又要透過加一個 class 的方式來改變字級,應該怎麼做?
//CSS 一樣要先寫好一個新的 class,假設要把字級變大,增加到 100px.style{font-size: 100px}//JSelement.setAttribute('class', 'style')
title text 的字級就會很明顯的變大了!
因此這樣比較起來,getAttribute 可以用來取屬性的值、串資料用,而 setAttribute 語法則可以透過改變 DOM 的屬性名稱與屬性的值,進而做動態的改變,兩者語法看起來雖然很相似,用法卻是很不相同!
更多相關範例可參考 codepen