JS之setAttribute和getAttribute

时间:2023-03-09 13:40:54
JS之setAttribute和getAttribute

1.ele.getAttribute(attributeName);

返回元素的指定属性值,如果元素没有该属性,则返回null

2.ele.setAttribute(attributeName,value);

为元素指定属性设置值,如果没有该属性,则创建该属性,并赋值

3.在IE 7以及更早版本部分属性的设置应使用另外的名称,为了兼容IE

<script>
           dom=(function(){
           var fixAttr={
                  tabindex:'tabIndex',
                  readonly:'readOnly',
                  'for':'htmlFor',
                  'class':'className',
                  maxlength:'maxLength',
                  cellspacing:'cellSpacing',
                  cellpadding:'cellPadding',
                  rowspan:'rowSpan',
                  colspan:'colSpan',
                  usemap:'useMap',
                  frameborder:'frameBorder',
                  contenteditable:'contentEditable'
           },

           //模拟设置attribute,
          div=document.createElement('div');
          div.setAttribute('class','t');

          var supportSetAttr = div.className === 't';

           return {
                   setAttr:function(el, name, val){
                        el.setAttribute(supportSetAttr ? name : (fixAttr[name] || name), val);
                   },
                   getAttr:function(el, name){
                        return el.getAttribute(supportSetAttr ? name : (fixAttr[name] || name));
                    }
              }
        })();

        window.onload=function(){
               var mydiv=document.getElementById("d1");
               dom.setAttr(mydiv, 'class', 'bg');
        }
    </script>

在IE 7以及更早版本中,setAttribute('class','fo');能为元素添加class='fo'.

getAttribute('class');能返回fo值,但是为元素添加的类不起作用,应为IE 7及更早版本的类设置用className,而不是class

 4.

getAttribute(attributeName);不仅可以得到元素默认属性值,还能得到自定义属性值

ele.attributeName或者ele['attributeName']只能得到元素默认存在的属性值

5.

var node = ele.getAttributeNode(attributeName)得到属性节点

console.log(node);//name=value的形式
console.log(node.name);
console.log(node.value);
<body>
    <p id="p1" customData="pmx">ppp</p>
    <script>
       var p = document.getElementById("p1");
       var pnode = p.getAttributeNode("customData");
       console.log(pnode)
    </script>
</body>

JS之setAttribute和getAttribute

JS之setAttribute和getAttribute

JS之setAttribute和getAttribute

6.ownerElement返回属性节点所附属的元素

语法:

  attrObj.ownerElement