JS中Attribute和property的区别

在使用angular中的数据绑定时,发现对HTML属性和DOM属性不是很清楚,顺便屡屡清楚这二者的区别。

Attribute:HTML属性,书写在标签内的属性,使用setAttribute()和getAttribute()进行设置和获取。

Property:DOM属性,html标签对应的DOM节点属性,使用 .属性名 或者 ['属性名']进行设置和获取。

<input id="inputId" class="inputClass" type="text" value="this is input" placeholder="test"/>

 如上可以看到HTML属性有:id、class、value、placeholder,通过attributes属性,也可以看到HTML属性,如下:

一、非自定义的Attribute与property之间存在映射关系

let input = document.getElementById('inputId');

console.log('property-class: '+input.className);
console.log('attribute-class: '+input.getAttribute('class'));
input.className = 'propertyClass';
console.log('---property-change---');
console.log('property-class: '+input.className);
console.log('attribute-class: '+input.getAttribute('class'));
input.setAttribute('class','attributeClass');
console.log('---attribute-class---');
console.log('property-class: '+input.className);
console.log('attribute-class: '+input.getAttribute('class'));

从输出结果可以看出,不管是修改attribute还是property都会影响到对方的属性值。

【注意点】

 1、value属性,不存在映射关系,property的修改和attribute的修改,都不会影响到对方。

let input = document.getElementById('inputId');

console.log('property-value: '+input.value);
console.log('attribute-value: '+input.getAttribute('value'));
input.value = '123456';
console.log('---property-change---');
console.log('property-value: '+input.value);
console.log('attribute-value: '+input.getAttribute('value'));
input.setAttribute('value','099800');
console.log('---attribute-value---');
console.log('property-value: '+input.value);
console.log('attribute-value: '+input.getAttribute('value'));

从输出结果可以看出,如果不对attribute上的value属性进行修改的话,那么,attribute上的value属性一直保留初始值,而property的上的value值是当前值,也就是在input上输入的值改变,那么property上的值也会跟着改变。

二、自定义Attribute,在property上没有对应的属性

自定义的属性,在property上是不存在的,修改或者获取都只能通过setAttribute()或getAttribute()

<input id="inputId" type="text" value="123" data-test="自定义属性test"/>
<script>
   let inputId = document.getElementById('inputId');
   console.log('获取:'+inputId.getAttribute('data-test'));
   console.log('设置后:'+inputId.getAttribute('data-test'));
</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值