JS中DOM元素的attribute与property

本文主要探讨了JS中attribute与prototype的区别、使用及相关案例。attribute是dom元素在文档中作为html标签的属性,值为字符串且不能改变;prototype是dom元素在js中作为对象的属性,值可改变且能赋任意类型。还介绍了二者在创建、数据绑定和使用方面的特点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

定义的区别

  • attribute
    1.是dom元素在文档中作为html标签拥有的属性;
    2.其值不能改变
    3.只能赋值为字符串
  • prototype
    1.是dom元素在js中作为对象拥有的属性
    2.其值可以改变
    3.可以赋任何类型的值

以上是较浅的区别,以下继续深入探讨

对比二者的使用

  • 打印属性 attribute
//html
<div class="divClass" id="divId"></div>

//javascript
var divId = document.getElementById('divId');
	console.log(divId.attributes);

此时会打印出它的attributes对象(如下图):
Alt
此时让我们对attributes对象的值进行查看

console.log(divId.attributes[0]); //打印 class="divClass"
console.log(divId.attributes.class) //打印 class="divClass"
 
console.log(divId.getAttribute('class')) //打印divClass
console.log(divId.getAttribute('id')) //打印divId

可以看出两组的值相等。

  • 打印属性prototype

html自带的dom属性会自动转化成prototype,这里可以把标签div看作一个对象,使用’.'来输出即为protopyte属性。
但是不包含自定义属性,既prototype不能输出自定义属性。

<div class="divClass" id="divId" addArrt="add"></div>
 
console.log(divId.class);  //打印 divClass
console.log(divId.addArrt) //打印 undefined

可以看出prototype,dom存在的属性,property同样继承了,而addArrt却没有出现在property中
Alt

案例剖析

让我们来修改prototype

//html
<input value="initValue" id="ipt"/>
 
//js
 var ipt = document.getElementById('ipt');
 
 ipt.value = 'changeValue'
 console.log(ipt.value);
 console.log(ipt.getAttribute('value'));

先自己判断一下打印的值。

当当当当!!!
真正的答案揭晓:

console.log(ipt.value);   //changeValue
console.log(ipt.getAttribute('value'));  //initValue

现在再来看看修改attritube会怎么样

//html
<input value="initValue" id="ipt"/>
 
//js
 var ipt = document.getElementById('ipt');
 
 ipt.setAttribute('value','changeValue')
 console.log(ipt.value);
 console.log(ipt.getAttribute('value'));

输出如下:

console.log(ipt.value);   //changeValue
console.log(ipt.getAttribute('value'));  //changeValue
分析了这么多,来总结一下:

创建

  • DOM对象初始化时会在创建默认的基本property;
  • 只有在HTML标签中定义的attribute才会被保存在property的attributes属性中;
  • attribute会初始化property中的同名属性,但自定义的attribute不会出现在property中;
  • attribute的值都是字符串;
    数据绑定
  • attributes的数据会同步到property上,然而property的更改不会改变attribute;
  • 对于value,class这样的属性/特性,数据绑定的方向是单向的,attribute->property;
  • 对于id而言,数据绑定是双向的,attribute<=>property;
  • 对于disabled而言,property上的disabled为false时,attribute上的disabled必定会并存在,此时数据绑定可以认为是双向的;
    使用
  • 可以使用DOM的setAttribute方法来同时更改attribute;
  • 直接访问attributes上的值会得到一个Attr对象,而通过getAttribute方法访问则会直接得到attribute的值;
  • 大多数情况(除非有浏览器兼容性问题),jQuery.attr是通过setAttribute实现,而jQuery.prop则会直接访问DOM对象的property;

文章参考:here

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值