iT邦幫忙

1

HTML Attributes 與 DOM Properties 的區別

717 2019-06-22 11:53:145232 瀏覽
  • 分享至 

  • xImage
  •  

 之所以寫這篇文章,只因在學習HTML5及Angular的過程,直接將attributes與properties搞混了,畢竟中文翻譯都叫「屬性」,在使用上(對菜鳥而言)差異又是若有似無,因此為了區別,我想整理一下目前對HTML及DOM的理解,以及HTML Attributies及DOM Properties的差異,希望能幫助到你妳祢,如果在文章中發現任何我對它們的誤解,也歡迎指正(*´ω`)人(´ω`*)。

Attributes與Properties怎麼出現的?

 我們在網頁中使用HTML標籤,並對這些標籤們設定attributes,而當瀏覽器解讀HTML時,瀏覽器會產生相應的DOM node,這個DOM node其實就是個物件、而物件就會有它的Properties。

HTML Attributes 與 DOM Properties是怎樣的存在?

 你知道HTML是個標記語言、XML也是(當然還有其他很多),所以它們都是靠attributes設定的;而DOM是Document Object Model的縮寫,它就是個物件(Object),就是靠Properties運作的喔。

 DOM其實是個獨立的存在,雖然我們在寫HTML5時,大多都用JavaScript來操作它的Properties,不過其它語言、例如Python也是可以使用DOM Properties的。

HTML Attributes跟DOM Properties長怎樣?

 那麼我們就來看看HTML Attributes跟DOM Properties到底長怎樣吧,在這裡我們先創個HTML 的input標籤:

<input type="text" id="inputBox" value="Hello!">

 然後使用JavaScript來取得的一個名叫.attributes的DOM Property,來取得此input標籤的attributes們。
 並且繼續使用名叫.name.value的DOM Properties,來取得input標籤的Attributes的名字與值。

//先從DOM中抓到id是inputBox的那位
const inputBox = document.getElementById('inputBox'); 
//然後再取得它的attributes
const attrs = inputBox.attributes; 
//最後使用for迴圈印出它擁有的attributes名字與值
for(var i = attrs.length - 1; i >= 0; i--) { 
  console.log(`${attrs[i].name} ==>  ${attrs[i].value}`);
} 
//這就是我們得到的結果
// id ==>  inputBox
// value ==>  Hello!
// type ==>  text

 就...當DOM node生成的時候,很多DOM Properties都跟HTML attributes有同樣的名字,但卻又不能說它們就是一樣的,怎麼說呢?看看上方的例子,id與type基本上它們的DOM Properties與HTML attributes有一樣的結果,不過value就難說了:

const inputBox = document.getElementById('inputBox');

console.log(
  inputBox.id === inputBox.getAttribute('id') // true
);

console.log(
  inputBox.type === inputBox.getAttribute('type') // true
);

setTimeout(() => {
  console.log(
    inputBox.value === inputBox.getAttribute('value') // false if value changed
  );
  console.log(`inputBox.value is ${inputBox.value} and inputBox.getAttribute('value') is ${inputBox.getAttribute('value')}`);
}, 5000);

 慢5秒印出value是為了讓我們在input框內輸入一些文字,此時就會發現.getAttribute()印出的是我們編輯HTML時寫在裡的value值、也就是Hello!,而.value則是我們在input框中輸入的即時的值。

 雖然DOM Properties與HTML attributes常有一樣的名字、也常有一樣的值,不過value就是網頁開發時,一定會遇到的DOM Properties與HTML attributes不一樣的例子。

多多參考W3C與F12

看看HTML attributes吧

 在W3C查詢HTML標籤時,它很好心的將此標籤可使用的attributes列表出來了。

DOM properties藏在這

 在網頁中按下F12檢查網頁時,雖然比較常看CSS style怎麼又沒吃到了呢(#`Д´)ノ,其實在styles分頁的隔壁隔壁隔壁,有個名叫Properties的鄰居,在這裡就可以看到目前選到的HTML標籤,它所擁有的>HTML某標籤Element Properties了喔^^。

本文參考、翻譯自HTML Attributes vs DOM Properties By TAMAS PIROS


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言