操作元素屬性的多種方式
setAttribute getAttribute removeAttribute
操作html的屬性(attribute)
<input type="text" id="text1" value="11" data-name="input"/>
<script>
var oText = document.getElementById('text1');
//元素.getAttribute(屬性名稱); 方法 獲取指定元素的指定屬性的值
alert( oText.getAttribute('data-name') )
// 元素.setAttribute(屬性名稱上枕,屬性值); 方法 給指定元素指定的屬性設(shè)置值
oText.setAttribute( 'data-name', 'hello' );
//元素.removeAttribute(屬性名稱); 方法 移除指定的元素的指定的屬性
oText.removeAttribute( 'data-name' );
</script>
DOM的屬性(property)
DOM是對(duì)象, 它的屬性操作跟我們對(duì)象的操作是一樣的
oText.value = 'hello';
oText['value'] = 'hello';
alert(oText.value);
由于HTML的Attribute和DOM的Property在中文中都被翻譯成了“屬性”
但它們是完全不同的東西
HTML 的 Attribute 和 DOM 的 Property 比較
Attribute 是由 HTML 定義的咐熙。 Property 是由 DOM(Document Object Model) 定義的。
- 少量 HTML Attribute 和 Property 之間有著 1:1 的映射辨萍。 id 就是一個(gè)例子棋恼。
- 有些 HTML Attribute 沒有對(duì)應(yīng)的 Property 。 colspan 就是一個(gè)例子。
- 有些 DOM Property 沒有對(duì)應(yīng)的 Attribute 蘸泻。 textContent 就是一個(gè)例子琉苇。
- 大量 HTML Attribute 看起來映射到了 Property ……但卻不像我們想象的那樣!
尤其最后一種更讓人困惑……除非我們能理解這個(gè)普遍原則:
Attribute 初始化 DOM Property 悦施,然后它們的任務(wù)就完成了
Attribute 會(huì)影響property, propery的值不會(huì)影響attribute
<input type="text" value="bob">
<script>
var input = document.getElementsByTagName('input')[0];
input.value;//bob
//改變property的值
input.value = 'Sally';
//或者直接在輸入框中輸入'Sally'
input.getAttribute('value');//bob 還是bob propery的值不會(huì)影響attribute
input.setAttribute('value', 'hellen');
input.value;//hellen;
</script>