码迷,mamicode.com
首页 > 其他好文 > 详细

setAttribute和getAttribute

时间:2016-08-30 19:27:49      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:

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);
 

 

setAttribute和getAttribute

标签:

原文地址:http://www.cnblogs.com/pmx-pmx/p/5823017.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!