Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

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"
"https://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] 在火狐22版本之前,这个属性是被用在 Node 上 (继承至 Element). 它需要被使用在其他符合这个接口规范的浏览器上使用。

[2] IE5.5返回的是一个map形式的键值对而不是一个attribute的属性对象。

相关链接

文档标签和贡献者

 此页面的贡献者: MeCKodo, teoli, AlexChao, khalid32, ziyunfei, Mgjbot, Dewang
 最后编辑者: MeCKodo,