在dom结构中是属性子节点还是兄弟节点?

时间:2013-08-07 12:01:39

标签: javascript html dom

假设我有一个带有title属性的段落元素。由于DOM结构中的所有内容都是一个节点,p和title属性之间的关系是什么?他们是兄弟姐妹,还是<p>或兄弟姐妹的子节点的标题属性?我可以使用nodeValue属性访问title属性的内容吗?

1 个答案:

答案 0 :(得分:9)

具有属性节点的元素是属性节点的.ownerElement。否则没有树状关系 - 属性节点的兄弟节点,parentNode等是空的。

http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-637646024

  

Attr对象继承Node接口,但因为它们不是   实际上他们描述的元素的子节点,DOM没有   将它们视为文档树的一部分。因此,Node属性   parentNode,previousSibling和nextSibling的值为null   Attr对象。

关系是:

var p = document.createElement("p");
p.title = "hello";

var titleAttr = p.attributes.title //from the element to the attribute

p = titleAttr.ownerElement //from the attribute node to the owning element
  

我可以使用nodeValue属性

访问title属性的内容

如果您有属性节点,则可以使用以下命令访问密钥/名称

titleAttr.nodeName; //"title"

您可以使用以下方式访问该值:

titleAttr.nodeValue; //"hello"

.nodeType还是2Node.ATTRIBUTE_NODE