iT邦幫忙

2021 iThome 鐵人賽

DAY 4
0
Modern Web

網頁前後端寶石庫-礦坑補完計畫系列 第 4

Day 04 HTML/JavaScript Attribute vs Property

  • 分享至 

  • twitterImage
  •  

Attribute vs Property

  • attribute:屬性在 HTML 會被稱為 attribute,href is attribute of a。
  • property:屬性在 JS 會被稱為 property,id is property of a。

範例

<a href="#" id="777"></a>
a.id="777"

Attribute 及 Property 雖然在英文上是兩個不同的詞,但中文同樣都翻譯成屬性。
究竟兩者到底有甚麼差異呢?
在探討這個問題前,先來看看甚麼是 DOM 吧。

DOM(Document Object Model,文件物件模型)

DOM 主要是用來把 HTML 文件的元素變成物件,存取後拿來 JS 裡使用。

範例

<h1 id = "title">學會React<h1>
<p class = "text">年薪百萬<p>

像是上面的範例在 JS 可以透過 document.querySelector 或是 document.getElementById 等方法抓取到 HTML 的元素拿到 JS 裡操作。

只要是 DOM 裡的物件都會有以下這些函式可以使用:
https://ithelp.ithome.com.tw/upload/images/20210916/20139241U6RJa5akRF.png
(如常見的 document.querySelector() 或是 EventTarget.addEventListener() 都是這邊提供的)。

DOM Tree

類似生物分類表,用來分類元素,元素當中 html 在最上層,下層則有 head、body 等元素,依階層慢慢分類下去。
https://ithelp.ithome.com.tw/upload/images/20210916/20139241JFZGyg2HtQ.png

Attribute and Property

現在回到 Attribute 及 Property。
當瀏覽器在讀取頁面時,他會解析 HTML 並產生 DOM 物件。
對於大部分的節點,HTML 的 Attribute 都會自動被轉換成 DOM 物件的 Property。

範例:

<body id = "title">

會被轉換成:

body.id="title"

HTML attributes

  • attributes 的值一定是字串。
  • 沒有大小寫的區分(id = ID)
    每個元素都有他們各自的標準 attributes,有些是通用的,有些是限定的。
    如果不是標準或是限定的 attributes,那就不會產生對應的 DOM properties。
    這時候就無法透過一般的方法去操作這個 attribute。
  • 非標準:就是亂寫,如:hello、5xruby。
  • 通用的:在各元素上都可以添加,如:id、class。
  • 限定的:只能在特定元素上添加,如:type 可以添加在 input 元素內,但如果添加在 div 內就不會產生對應的 DOM properties。

DOM properties

操作 properties 跟操作 JS 的物件及函式是很像的:

  • 可以幫他們添加任何值。
  • 有大小寫的區分(是 addEventListener,不是 addeventlistener)。

那要怎麼抓到那些不會產生對應的 DOM properties 的 attributes 呢?

  • 可以透過以下方法抓到:
    • Element.hasAttribute(name) – 確認是否有這個屬性。
    • Element.getAttribute(name) – 抓到這個屬性的值。
    • Element.setAttribute(name, value) – 設定這個屬性的值。
    • Element.removeAttribute(name) – 移除這個屬性。

假如我需要自訂一個非標準的 attributes 該怎麼辦?

這時候 data 屬性就可以派上用場了,在 HTML 以 data- 開頭的可以在 JS 裡面用 dataset 拿到。

範例

<div id="user" data-id="777" data-user="kirito">幫我撐10秒</div>

在 JS 可以用 dataset property 拿到。

const Beater = document.querySelector("#user");
Beater.id === "user"
Beater.dataset.id === "777"
Beater.dataset.user === "kirito"

參考:
[1]MDN:DOM
[2]wiki:DOM Tree
[3]Web開發學習筆記11 — DOM、Attribute與Property的差異
[4]Attributes and properties
[5]HTMLElement.dataset


上一篇
Day 03 HTML/CSS 使用 tailwindcss 遇到的小問題
下一篇
Day 05 JavaScript 同步(Sync) vs 非同步(Async)處理
系列文
網頁前後端寶石庫-礦坑補完計畫30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言