DOM-->操作元素屬性多種方式

操作元素屬性的多種方式

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>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容