Element.attributes

摘要

Element.attributes 属性返回该元素所有属性节点的一个即时更新(live)的集合。该集合是一个 NamedNodeMap 对象,不是一个数组,所以它没有 数组 的方法,其包含的 属性 节点的索引顺序随浏览器不同而不同。更确切地说,attributes 是字符串形式的名/值对,每一对名/值对对应一个属性节点。

语法

var attr = element.attributes;

示例

基本示例

// 获取文档的第一个 <p> 元素
var para = document.getElementsByTagName("p")[0];
var atts = para.attributes;

遍历元素的属性节点

当遍历元素的所有属性时,可使用索引。在以下例子中,打印文档中“p1”元素的所有属性:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">

<html>

 <head>
  <title>Attributes example</title>
  <script type="text/javascript">
   function showFirstAttr() 
   {
    var firstPara = document.getElementById("p1");
    var outputText = document.getElementById("result");

    // First, let's verify that the paragraph has some attributes    
    if (firstPara.hasAttributes()) 
    {
      var attrs = firstPara.attributes;
      var text = ""; 
      for(var i=attrs.length-1; i>=0; i--) {
        text += attrs[i].name + "->" + attrs[i].value + "<br>";
      }
      outputText.innerHTML = text;
    } else {
      outputText.value = "No attributes to show"
    };
   }
  </script>
 </head>

<body>
 <p id="p1" style="color: green;">Sample Paragraph</p>
 <form action="">
  <p><input type="button" value="Show first attribute name and value"
      onclick="showFirstAttr();">
  <p id="result"></p></p>
 </form>
</body>
</html>

规范

Specification Status Comment
DOM
Element.attributes
Living Standard From Document Object Model (DOM) Level 3 Core Specification, moved from Node to Element
Document Object Model (DOM) Level 3 Core Specification
Element.attributes
Recommendation No change from Document Object Model (DOM) Level 2 Core Specification
Document Object Model (DOM) Level 2 Core Specification
Element.attributes
Recommendation No change from Document Object Model (DOM) Level 1 Specification
Document Object Model (DOM) Level 1 Specification
Element.attributes
Recommendation Initial definition.

浏览器兼容性

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support (Yes) (Yes) [1] 6.0 [2] (Yes) (Yes)
Feature Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support (Yes) (Yes) [1] (Yes) (Yes) (Yes)

[1] Before Firefox 22, this attribute was implemented in the Node interface (inherited by Element). It has been moved to this interface to conform to the specification and the usage of other browsers.

[2] Internet Explorer 5.5 returns a map containing the values rather than the attribute objects.

相关链接

文档标签和贡献者

向此页面作出贡献: teoli, AlexChao, khalid32, ziyunfei, Mgjbot, Dewang
最后编辑者: AlexChao,
隐藏侧边栏