aboutsummaryrefslogtreecommitdiff
path: root/files/zh-cn/web/api/element/setattributenode/index.html
blob: 1d9c641c8e3c564d27b82c3f28eab850988f3508 (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.setAttributeNode()
slug: Web/API/Element/setAttributeNode
tags:
  - API
  - DOM
  - Element
translation_of: Web/API/Element/setAttributeNode
---
<p>{{ APIRef("DOM") }}</p>

<p><code>setAttributeNode()</code> 为指定的 Element 添加属性节点.</p>

<h2 id="Syntax" name="Syntax">Syntax</h2>

<pre class="eval"><em>var replacedAttr</em> = <em>element</em>.setAttributeNode(<em>attribute</em>);
</pre>

<ul>
 <li><code>attribute是添加到 element 中的属性节点</code>.</li>
 <li><code>replacedAttr</code> 是被替换掉的属性节点。 如果存在原有属性, 则函数返回原有属性节点. </li>
</ul>

<h2 id="Example" name="Example">Example</h2>

<pre>// &lt;div id="one" align="left"&gt;one&lt;/div&gt;
// &lt;div id="two"&gt;two&lt;/div&gt;
var d1 = document.getElementById("one");
var d2 = document.getElementById("two");
var a = d1.getAttributeNode("align");
d2.setAttributeNode(a.cloneNode(true));
alert(d2.attributes[1].value)
// returns: `left'
</pre>

<h2 id="Notes" name="Notes">Notes</h2>

<p>如果 element 中已经存在该属性名的属性,则函数使用新的属性替换掉原有的属性并将原有属性返回</p>

<p>这个方法很少被用到, 多数情况下使用函数 <code><a href="/en/DOM/element.setAttribute" title="en/DOM/element.setAttribute">setAttribute()</a></code> 修改 element 的属性.</p>

<p>{{ DOMAttributeMethods() }}</p>

<h2 id="Specification" name="Specification">Specification</h2>

<p><a class="external" href="http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-887236154">DOM Level 2 Core: setAttributeNode</a> (introduced in <a class="external" href="http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#method-setAttributeNode">DOM Level 1 Core</a>)</p>