aboutsummaryrefslogtreecommitdiff
path: root/files/pt-br/web/api/node/replacechild/index.html
blob: e6d78e31210d3b15048dd565fa2c5106f8eb388b (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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
---
title: Node.replaceChild
slug: Web/API/Node/replaceChild
translation_of: Web/API/Node/replaceChild
---
<div>
<div>{{ApiRef("DOM")}}</div>
</div>

<h2 id="Summary" name="Summary">Sumário</h2>

<p>Substitui o elemento filho especificado por outro.</p>

<p><strong style="font-size: 2.142857142857143rem; font-weight: 700; letter-spacing: -1px; line-height: 30px;">Sintaxe</strong></p>

<pre class="syntaxbox"><em>replacedNode</em> = <em>parentNode</em>.replaceChild(<em>newChild</em>, <em>oldChild</em>);
</pre>

<ul>
 <li><code>newChild</code> é o novo elemento que será inserido no lugar do <code>oldChild</code>. Se já existir no DOM, será removido primeiro para depois ser inserido.</li>
 <li><code>oldChild</code> é o elemento existente que será substituído.</li>
 <li><code>replacedNode</code> é elemento substituído. É o mesmo elemento que <span style="font-family: 'Courier New','Andale Mono',monospace;">oldChild.</span></li>
</ul>

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

<pre class="brush:js">// &lt;div&gt;
//  &lt;span id="childSpan"&gt;foo bar&lt;/span&gt;
// &lt;/div&gt;

// Cria um novo elemento vazio
// sem ID, atributos ou conteúdo
var sp1 = document.createElement("span");

// Adiciona um ID 'newSpan' para o elemento
sp1.setAttribute("id", "newSpan");

// Adiciona contéudo para o elemento
var sp1_content = document.createTextNode("new replacement span element.");

// Coloca o conteúdo no elemento
sp1.appendChild(sp1_content);

// Procura o elemento que será substituído
var sp2 = document.getElementById("childSpan");
var parentDiv = sp2.parentNode;

// Substituí o elemento que já existe (sp2) por o novo elemento (sp1)
parentDiv.replaceChild(sp1, sp2);

// resultado:
// &lt;div&gt;
//   &lt;span id="newSpan"&gt;new replacement span element.&lt;/span&gt;
// &lt;/div&gt;
</pre>

<h2 id="Specification" name="Specification">Especificação</h2>

<ul>
 <li><a href="http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#method-replaceChild">DOM Level 1 Core: replaceChild</a></li>
 <li><a href="http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-785887307">DOM Level 2 Core: replaceChild</a></li>
 <li><a href="http://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-785887307">DOM Level 3 Core: replaceChild</a></li>
</ul>

<h2 id="See_also" name="See_also">Veja também</h2>

<ul>
 <li>{{domxref("Node.removeChild")}}</li>
</ul>