javascript - DOM Attr 类使用示例

标签 javascript html dom domdocument

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

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

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

请有人能给我一个用法示例来启发我何时使用 Attr直接类,因为它没有构造函数,而且据我所知不能传递给 DOM 中的任何方法?

引用:

最佳答案

它有用的一件事是,当 DOM 文档是 XML document 时你想知道 namespace URInamespace 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 上的 DOM 规范尚不明确(请参阅 8.2 DOM Core 部分中的警告),whatwg 上的 DOM 规范也不是

关于javascript - DOM Attr 类使用示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44717498/

相关文章:

javascript - 停止某些链接(包含特定字符串的 href)工作

javascript - 如何统计其父元素第一行的元素个数

javascript - 使用 JS 和 CSS 更改页面样式?

javascript - 根据值更改 td 背景颜色

java - 使用 Jsoup 从 html 中提取注释

javascript - IndexedDB - ObjectStores vs 多个数据库 vs 索引?

javascript - 大数据集可视化

javascript - 迭代状态变量

jquery - 如何在 Kendo 日期时间选择器中将默认日期时间设置为空

javascript - 我们如何检测影子根是使用 v0 还是 v1 API 创建的?