標籤:
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