--- title: Element.getAttribute() slug: Web/API/Element/getAttribute tags: - Element.getAttribute() translation_of: Web/API/Element/getAttribute --- <div>{{APIRef("DOM")}}</div> <h2 id="Summary" name="Summary">概要</h2> <p><span><strong><code>getAttribute()</code></strong> 返回元素上</span>一个指定的属性<span>值。</span>如果指定的属性不存在,则返回 <code>null</code> 或 <code>""</code> (空字符串);具体细节, 请参阅 {{Anch("Notes")}} 部分。</p> <h2 id="Syntax" name="Syntax">语法</h2> <pre class="syntaxbox"><em>let attribute</em> = element.getAttribute(<em>attributeName</em>); </pre> <p>上面:</p> <ul> <li><code><em>attribute</em></code> 是一个包含 <code><em>attributeName</em></code> 属性值的字符串。</li> <li><code><em>attributeName</em></code> 是你想要获取的属性值的属性名称。</li> </ul> <h2 id="Example" name="Example">例子</h2> <pre class="brush:js">let div1 = document.getElementById("div1"); let align = div1.getAttribute("align"); alert(align); // shows the value of align for the element with id="div1"</pre> <h2 id="Notes" name="Notes">备注</h2> <p>当在被标记为 HTML 文档中的一个 HTML 元素上调用此方法时,<code>getAttribute()</code> 会先将其参数转换为小写形式。</p> <p>当指定的属性不存在于元素上时,所有浏览器(Firefox、Internet Explorer、Opera 最新版本、Safari、Konqueror 以及 iCab 等等)都返回 <code>null</code>,这也是<a href="http://dom.spec.whatwg.org/#dom-element-getattribute" title="http://dom.spec.whatwg.org/#dom-element-getattribute">当前 DOM 规范草案</a>规定的。然而,旧的DOM 3 Core specification 认为此时正确的返回值应该是一个空字符串,一些 DOM 实现环境实现了该行为(behavior)。在 XUL (Gecko) 中,getAttribute 的实现遵从 DOM 3 Core specification,返回一个空字符串。因此,如果一个属性可能不存在于指定的元素上,在调用 <code>getAttribute()</code> 之前,你应该使用 {{domxref("element.hasAttribute()")}} 来检测该属性是否存在。</p> <h2 id="浏览器兼容性">浏览器兼容性</h2> <p>{{CompatibilityTable}}</p> <table> <tbody> <tr> <th>Feature</th> <th>Chrome</th> <th>Edge</th> <th>Firefox (Gecko)</th> <th>Internet Explorer</th> <th>Opera</th> <th>Safari</th> </tr> <tr> <td>Basic support</td> <td>29</td> <td>{{CompatVersionUnknown}}</td> <td>23</td> <td>{{CompatVersionUnknown}}</td> <td>{{CompatVersionUnknown}}</td> <td>6</td> </tr> </tbody> </table> <p>{{DOMAttributeMethods}}</p> <h2 id="Specification" name="Specification">规范</h2> <ul> <li><a class="external" href="http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-666EE0F9">DOM Level 2 Core: getAttribute</a> (introduced in <a class="external" href="http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#method-getAttribute">DOM Level 1 Core</a>)</li> <li><a class="external" href="http://www.whatwg.org/specs/web-apps/current-work/multipage/dom.html#apis-in-html-documents">HTML 5: APIs in HTML documents</a></li> </ul>