blob: 15235c37bfc5cb78b9b483123c4c88cb9afc01b3 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
---
title: Element.getAttribute()
slug: Web/API/Element/getAttribute
translation_of: Web/API/Element/getAttribute
---
<div>{{APIRef("DOM")}}</div>
<h2 id="Summary" name="Summary">摘要</h2>
<p><span class="seoSummary"><code>getAttribute()</code> 函式會回傳該網頁元素的屬性</span>。 如果該屬性不存在,其回傳值會是<code>null或</code> <code>""</code> (空字串); 詳見 {{Anch("Notes")}} 。</p>
<h2 id="Syntax" name="Syntax">語法</h2>
<pre class="syntaxbox"><em>var </em><code><em>attribute</em></code> = element.getAttribute(<code><em>attributeName</em></code>);
</pre>
<p>where</p>
<ul>
<li><code><em>attribute</em></code> is a string containing the value of <code><em>attributeName</em></code>.</li>
<li><code><em>attributeName</em></code> is the name of the attribute whose value you want to get.</li>
</ul>
<h2 id="Example" name="Example">Example</h2>
<pre class="brush:js">var div1 = document.getElementById("div1");
var align = div1.getAttribute("align");
alert(align); // shows the value of align for the element with id="div1"</pre>
<h2 id="Notes" name="Notes">Notes</h2>
<p>When called on an HTML element in a DOM flagged as an HTML document, <code>getAttribute()</code> lower-cases its argument before proceeding.</p>
<p>Essentially all web browsers (Firefox, Internet Explorer, recent versions of Opera, Safari, Konqueror, and iCab, as a non-exhaustive list) return <code>null</code> when the specified attribute does not exist on the specified element and this is what <a href="http://dom.spec.whatwg.org/#dom-element-getattribute" title="http://dom.spec.whatwg.org/#dom-element-getattribute">the current DOM specification draft</a> specifies. The old DOM 3 Core specification, on the other hand, says that the correct return value in this case is actually the <em>empty string</em>, and some DOM implementations implement this behavior. The implementation of getAttribute in XUL (Gecko) actually follows the DOM 3 Core specification and returns an empty string. Consequently, you should use {{domxref("element.hasAttribute()")}} to check for an attribute's existence prior to calling <code>getAttribute()</code> if it is possible that the requested attribute does not exist on the specified element.</p>
<h2 id="Browser_compatibility">Browser compatibility</h2>
{{Compat("api.Element.getAttribute")}}
<h2 id="Specification" name="Specification">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>
|