HTML 的 attribute 和 JS 的 property 的異同詳解
同樣是獲得 element 的 style 屬性,有兩種方式 el.style 和 el.getAttribute(‘style’) 。前者我們叫 style 是 el 的 property ,後者我們叫style 是 el 的 attribute。
attribute
attribute 是HTML DOM 物件自帶(特有)的屬性,在 html 中顯式的設定,例如 id,class ,value 等。它的值只能是字串。
<input type='text' id='hjh' name='haha' />
<script>
var hjh = document.getElementById('hjh');
console.log(hjh.attributes);
</script>
attribute 有三個方法:setAttribute() , getAttribute() , removeAttribute()
var hjh = document.getElementById('hjh');
hjh.setAttribute('value', 'test');
console.log(a.getAttribute('name')); // haha
a.removeAttribute ('name');
console.log(a.getAttribute('name')); // null
Attribute的屬性值只能是字串,屬性鍵大小寫不敏感。
可以說,如果想要獲取一個DOM元素的attribute屬性值,只要開啟控制檯看看該DOM標籤的html程式碼,任何時候attribute值和html標籤內設定的屬性值都是同步的。
property
DOM 是 JavaScript 裡的物件,Property 是 DOM 中的屬性,它的屬性值主要通過點運算子來獲取和改變。這個物件實現了很多屬性(property):‘value’,'className’等,以及一些方法 getAttribute,setAttribute 等,它也可以和其他的 JavaScript 物件一樣新增自定義的屬性以及方法。property 的值可以是任何的資料型別,對大小寫敏感,自定義的 property 不會出現在 html 程式碼中,只存在 js 中。
<input type='text' id='hjh' a='haha' />
<script>
var hjh = document.getElementById('hjh');
console.log(hjh.type);
console.log(hjh.id);
console.log(hjh.a);
console.log(hjh.title);
</script>
我們在 input 標籤中自定義了 a 屬性,可是在 property 中訪問為 undefined。沒有定義 title 屬性,卻返回了一個空值。
這是因為 html 標籤都有5個標準特性:id,title,lang,dir,className(在DOM中以property方式操作這幾個特性會同步到html標籤中)。所以即使在html中沒有指定id、title等,也會預設賦予一個空串,通過property屬性(點操作符)可以訪問。而除此之外在html中設定的其他屬性是不能通過Property訪問到的(除了attribute特有的屬性)。
如果把DOM元素看成是一個普通的Object物件,那麼property就是一個以名值對(name=‘value’)的形式存放在Object中的屬性。要新增和刪除property也和普通的物件沒啥分別:
var hjh = document.getElementById('hjh');
a.age = 10;
console.log(a.age); // 10
delete a.age;
console.log(a.age); // undefined
注意
很多attribute節點還有一個相對應的property屬性,比如div元素的id和class既是attribute,也有對應的property(id和className),不管使用哪種方法都可以訪問和修改,如果在TAG對這些屬性進行賦值,那麼這些值就會作為初始值賦給DOM的同名property。但也有一些比較特殊的:
- input 元素的 value
var a = document.getElementById('txt');
a.setAttribute('value', 'test');
console.log(a.value); // test
a.value = 'change';
console.log(a.getAttribute('value')); // test
用點操作符修改 value 值,並不會同步到 attribute 上;但是通過 setAttribute 修改屬性值,會同步到 property 上。
- 表單
<input type='radio' checked='checked' id='radio'>
<script>
var radio = document.getElementById('radio');
console.log(radio.getAttribute('checked')); // 'check'
console.log(radio.checked); // true
</script>
一些表單元素,對於這些特殊的 attribute 節點,只要存在該節點,對應的 property 就為true,disabled 類似
- href
<a href='a.html' id='web'> </a>
<script>
var radio = document.getElementById('web');
console.log(web.getAttribute('href')); // 'a.html'
console.log(web.href); // 絕度路徑
</script>
attribute 取得是相對路徑;property 取得是絕對路徑。
總結
attribute 屬性在 html 上設定,會反應在 html 上,兩者同步。property 屬性可以看作 DOM 物件的鍵值對,用點操作符修改。通常情況下,都使用 property 的點操作符對 DOM 進行操作。
以下兩種情況用attribute:
- 自定義 attribute 標籤,因為它不能同步到 property 上。
- 訪問內建的 html 標籤的 attribute,如 input 的 value(可以用來檢驗 value 值是否改變)