-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdomManipulationMethods.html
More file actions
81 lines (70 loc) · 2.42 KB
/
Copy pathdomManipulationMethods.html
File metadata and controls
81 lines (70 loc) · 2.42 KB
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
70
71
72
73
74
75
76
77
78
79
80
81
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript DOM: Como alterar o conteúdo de uma página HTML</title>
<style>
div{
display: flex;
flex-direction: column;
align-items: center;
}
h1{
margin: 25px auto;
text-align: center;
width: 100%;
background-color: darkkhaki;
font-family: sans-serif;
color: white;
}
#botao{
font-size: 2rem;
}
/*Criei essa regra CSS para testar se o stilo do H2 permanece após document.write()*/
h2{
background-color: red;
}
</style>
</head>
<body>
<div id="div">
<h1>HTML DOM</h1>
<input type="button" id="botao" value="Ativar!">
</div>
<script>
/*
Existem 3 maneiras de inserir HTML em um página com JS:
1. document.write() - nunca use! pq irá substituir todo o conteúdo da página.
2. innerHTML - usado com frequencia.
3. Métodos de manipulação do DOM - mais complexo porém te oferece maior controle sobre a página.
//1. documento.write() - utilizado somente para testar algum código.
//Ao clicar no botão todo o conteúdo da pagina será substituido pela Tag h2 com a string Hello Word dentro
function funcao(){
document.write("<h2>Hello World!</h2>")
}
//2. innerHTML exemple
var texto = "<h1>Lorem ipsum</h1> Lorem ipsum dolore et et duis minim ut aliqua aliquip laboris dolore. Officia sit nostrud nisi quis culpa sit veniam anim deserunt excepteur. Lorem ipsum occaecat anim tempor commodo veniam dolore ut pariatur voluptate nostrud do dolore occaecat elit laboris ullamco. Consequat culpa laborum laboris aliqua ad amet duis non elit velit excepteur qui voluptate ut minim eiusmod consectetur.";
var pegaDiv = document.getElementById("div");
pegaDiv.innerHTML = pegaDiv.innerHTML + texto;
//pegaDiv.innerHTML = texto;
console.log(pegaDiv.innerHTML);
*/
//3. DOM Manipulation methods: createElement, createTextNode, appendChild
function criarPara(){
//Criando a tag P e addcionando um texto nela
var para = document.createElement("p");
var node = document.createTextNode("Um novo parágrafo");
para.appendChild(node);
//Add o novo elemento <p> criado na <div> existente
var pegaDiv = document.getElementById("div");
pegaDiv.appendChild(para);
console.log(pegaDiv.innerHTML)
}
document.getElementById("botao").onclick=function(){
//funcao();
criarPara();
}
</script>
</body>
</html>