DOM元素的特性(attribute)和属性(property)区分

185 阅读2分钟

DOM元素的特性和属性区分

读者在学习的时候突然想到className和标签里class的关系,由此延申出来了dom元素attribute和property相关内容的整理和区分。

概念

特性(Attribute): 是DOM元素作为html标签拥有的属性 eg: id、class、type、align等,如图; 1.PNG

属性(Property):是DOM元素在js中作为对象拥有的属性 eg: className、style、firstChild等,如图:;

2.PNG

区别及使用方式

  • 特性(attribute)包括标准特性和自定义特性

    • DOM的五个标准特性包括id、title、lang、dir、class;
  • 部分attribute会转化为property 只要是DOM标签中出现的属性(html代码),都是Attribute,然后有些常用特性(id、class、title等),会被转化为Property。 3.PNG

    上图中的部分attribute会被转化为property,如下:

    4.PNG

    注意:“class”变成Property之后叫做“className”.

      const className = input.className;
      const className2 = input.getAttribute('class');
    
  • 取值和赋值

        .// dom元素如下
        <input id="ex-input" class="class-a" type="text" title1="title1" data-title="data-title" value="123" onclick="return 1">
        
        let input = document.getElementById('ex-input');
    

    attribute部分:

    • input.attributes() 获取一个该dom元素的所有attributes,值类型为NamedNodeMap 5.PNG

    • 获取/赋值attribute 6.PNG

    • getAttribute()可以取得任何特性,不管是标准的还是自定义的,但是这个方法的浏览器兼容性有问题,有些浏览器可能会获取属性Property的值

          input.className = 'a'; // 设置class property
          const judge = input.getAttribute("className") === 'a';// 在部分浏览器下面会为真,按理input.getAttribute应该为null
      
    • 对于标准特性来说,Attribute和Property是同步的,是会自动更新的

    • attribute的值只能为字符串,而property的值能为任意值,如下: 7.PNG

      • 以style和onclick为例:

          .// dom元素如下
           <input id="ex-input" class="class-a" type="text" title1="title1" data-title="data-title" value="123" onclick="return 1">
        
        
           let input = document.getElementById('ex-input');
           console.log(input.style);
        

        以上代码,返回了一个CSSStyleDeclaration对象,获取到的是style的property 8.PNG

        其对应的attribute(为一个字符串): 9.PNG

        再来看onclick对应的attribute和property10.PNG 也能发现,attribute一定为字符串,而property则为任意类型的值。

    property部分:

    • 属性取值很简单,用.操作符即可。
    const id = input.id;
    const className = input.className; // 对应特性中的class
    const childNodes = input.childNodes;
    const attrs = input.attributes;
    
    • 对于属性Property的赋值在IE中可能会引起循环引用,内存泄漏。

    附:

    • HTML5规范对自定义特性做了增强,只要自定义特性以"data-attrName"
       <input id="ex-input" class="class-a" type="text" title1="title1" data-title="data-title" value="123" onclick="return 1">
      
      获取以data开头的在自定义attribute 11.PNG

总结

  • 本文介绍了DOM元素的特性(Attribute)和属性(Property)的概念和区别,如有不对的地方,欢迎指正。

参考文章

  1. www.cnblogs.com/muhuck/p/10…

  2. www.cnblogs.com/wangfupeng1…

  3. www.cnblogs.com/moqiutao/p/…