JS中的“特性”与“属性” attribute与property

DOM元素的attribute和property很容易混倄在一起,分不清楚。特别区分一下。
  • attribute是HTML标签上的"特性",它的值只能够是字符串
  • property是DOM中的"属性",是JavaScript里的对象;

attribute节点都是在HTML代码中可见的,而property只是一个普通的名值对属性。

之所以attribute和property容易混倄在一起的原因是,很多attribute节点还有一个相对应的property属性,比如div元素的id和class既是attribute,也有对应的property,不管使用哪种方法都可以访问和修改。

但是对于自定义的attribute节点,或者自定义property,两者就没有关系了。

例如:

1、<div class="box" id="box" gameid="880">hello</div>

其中,gameid自定义属性,因此只能用getAttribute访问,无法用e.propName访问

console.log( elem.getAttribute('gameid') ); // 880

console.log(elem.gameid); //undefined

console.log( elem.removeAttribute('gameid') ); // undefined 删除

2、自定义property节点

elem.myColor = “red”; // 添加

console.log( elem.myColor ) // “red”

console.log(elem.getAttribute('myColor')); //null

delete elem.myColor // 删除

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值