全栈JavaScript之路(十一)学习 Attr 类型 节点

元素的特性在DOM 中用Attr 类型的节点表示。在全部浏览器中都能够訪问 Attr 类型的构造函数与原型。

从技术上讲,Attr 类型节点 就是指,元素的 Attrbutes 属性 中的节点。构造器函数为; function Attr() { [native code] }

虽然 也是称之为节点,可是:Attr 类型的节点不是文档树的一部分。


Attr 类型 节点 的特性:

  • nodeType:2
  • nodeName: 值为特性的名称
  • nodeValue: 值为特性的值
  • prasentNode:null
  • HTML中,不支持子节点
  • XML中,支持 Text 以及 EntityReference  两种类型节点。



操作Attr 类型节点最经常使用的三个方法;

  • getAttribute()
  • setAttribute()
  • removeAttribute()

另外还有,getAttributeNode(),setAttributeNode(),removeChild()


Attr 类型节点 有三个属性; name, value (值等同 nodeValue),specified( specified 是一个布尔值。用以差别特
性是在代码中指定的,还是默认的。)


创建 Attr 类型节点 document.createAttribute() ,创建之后 仅仅能使用 el.setAttribute(),方法将特性加入到元素。

var arr = document.createAttribute('align';)
arr.value = "center";
element.setAttributeNode(arr); //必须使用setAttributeNode() 方法

不建议直接訪问特性节点。最好通过上面介绍的方法訪问属性节点。


另一点要注意: 直接给DOM 加入属性,不会成为html 元素的特性。

div.mycolor = "red"; //不会成为 该 div 元素的 特性.
alert(div.getAttribute("mycolor")); //null(IE 除外)


原文地址:https://www.cnblogs.com/jhcelue/p/6951417.html