JS之setAttribute和getAttribute

來源:互聯網
上載者:User

標籤:

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>

 

 6.ownerElement返回屬性節點所附屬的元素

文法:

  attrObj.ownerElement

 

 

  

 

JS之setAttribute和getAttribute

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.