HTML中Attribute和JavaScript中property区别

Attribute是HTML标签中定义的属性

<div id="div" class="class" lang="ds" dir="ltr" title="title" userDefi="userDefi"></div>

例如上面定义的id,class,lang,dir,title,userDefi都是Attribute,都可以通过ele.getAttribute('id')这样获取其值。

Property是JavaScript为元素对象定义的属性

 var ele = document.getElementById('div');
    ele.anotherProp = 'anotherP';

例如上面为ele定义的anotherProp.

共同拥有的属性

虽然AttributeProperty定义的属性分别在不同层面上,但是有以下几个属性是共享的:

id
class
lang
dir
title


<div id="div" class="class" lang="ds" dir="ltr" title="title" userDefi="userDefi"></div>

    var ele = document.getElementById('div');
    ele.anotherProp = 'anotherP';
    ele.id = 'anotherId';
    console.log(ele.getAttribute('id'));//div
    console.log(ele.getAttribute('class'));//class
    console.log(ele.getAttribute('lang'));//ds
    console.log(ele.getAttribute('dir'));//ltr
    console.log(ele.getAttribute('title'));//title
    console.log('==============')
    console.log(ele.id);//div
    console.log(ele.className);//class
    console.log(ele.lang);//ds
    console.log(ele.dir);//ltr
    console.log(ele.title);//title
    console.log('==============')
    console.log(ele.anotherProp);//anotherP
    console.log(ele.getAttribute('anotherProp'));//null
    console.log(ele.getAttribute('userDefi'));//userDefi
    console.log(ele.userDefi);//undefined

    ele.id = 'anotherId';
    页面HTML标签同步显示id为anotherId

在页面改变input框的输入值并不会影响inputvalue

<input type="text" value="start" id="input">
<input type="button" value="changevalue" id="btn">
 btn.onclick = function () {
     input.value = 123;
     console.log(input.value);/123
     console.log(input.getAttribute('value'));//start
 };
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值