DOM Attr class 用法示例

DOM Attr class usage example

我正在做一个扩展 DOM 功能的项目,但我无法提供任何合理的例子来说明为什么 Attr class 存在,以及它可以做什么曾被用于。

鉴于 HTML 属性始终只是字符串,例如 <input type="date" name="your-birthday" />Element 原型上已经存在 setAttributegetAttribute 方法直接使用属性值作为字符串。

可以使用attr = element.attributes[0]获取Attr对象的引用,然后可以使用attr.value = "updated value";等方法进行交互。

有人可以用一个用法示例来启发我什么时候直接使用 Attr class ,因为它没有构造函数,据我所知不能传递给 DOM?

中的任何方法

参考:

它有用的一件事是,当 DOM 文档是属性的 XML document and you want to know the namespace URI or namespace prefix 时。

为了理解为什么这可能特别有用,我将在 Attr.namespaceURI 上引用 MDN 文档(强调我的):

Per the Namespaces in XML specification, an attribute does not inherit its namespace from the element it is attached to. If an attribute is not explicitly given a namespace, it has no namespace.

为了说明这一点,考虑这个例子,在这个例子中我们用 DOMParser 解析一个 XML 字符串来创建一个 XMLDocument 实例:

我特意给了<book>两个本地名称不明确的属性id,以说明它的用处。

const XML = '<?xml version="1.0" encoding="utf-8"?>\
<books xmlns:lib="http://example.com/xml/library">\
  <book id="book-one" lib:id="1">\
  </book>\
</books>';

var parser = new DOMParser;
var doc = parser.parseFromString( XML, 'application/xml' );

// is our Document an instance of XMLDOcument?
console.log( doc instanceof XMLDocument );

// fetch all Attr instances of the first <book> element
var attributes = doc.querySelector( 'book' ).attributes;
for( var attribute of attributes ) {
  // output namespace info about the Attr instance
  console.log( attribute.localName, attribute.prefix, attribute.namespaceURI, attribute.value );
}


另一个用例是,如果您想将 Attr 节点移动到另一个 Element:

div2.setAttributeNode( div1.removeAttributeNode( div1.getAttributeNode( 'class' ) ) );

当然,我不认为上面的示例是常见用法的示例。这可能就是为什么 Element.getAttributeNode()Element.getAttributeNodeNS()Element.setAttributeNode()Element.setAttributeNodeNS()marked as obsolete on MDN

但是,w3c.org are not as definitive yet (see the warning in section 8.2 DOM Core) and neither are the DOM specs on whatwg

上的 DOM 规范