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(属性名称,属性值); 方法 给指定元素指定的属性设置值
oText.setAttribute( 'data-name', 'hello' );

//元素.removeAttribute(属性名称); 方法 移除指定的元素的指定的属性
oText.removeAttribute( 'data-name' );


</script>

DOM的属性(property)

DOM是对象, 它的属性操作跟我们对象的操作是一样的

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 就是一个例子。
  • 有些 HTML Attribute 没有对应的 Property 。 colspan 就是一个例子。
  • 有些 DOM Property 没有对应的 Attribute 。 textContent 就是一个例子。
  • 大量 HTML Attribute 看起来映射到了 Property ……但却不像我们想象的那样!

尤其最后一种更让人困惑……除非我们能理解这个普遍原则:

Attribute 初始化 DOM Property ,然后它们的任务就完成了

Attribute 会影响property, propery的值不会影响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的值不会影响attribute

input.setAttribute('value', 'hellen');

input.value;//hellen;

</script>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容