Java script aula 06 - dom
-
Upload
cristiano-pires-martins -
Category
Internet
-
view
188 -
download
4
Transcript of Java script aula 06 - dom
Document Object Model - DOM
Cristiano Pires Martins
1
Referência: JavaScript - Guia do Programador - MAUJOR
http://www.w3c.br/cursos/html5 http://www.devmedia.com.br
Introdução• O navegador armazena sua interpretação do
código HTML como uma estrutura de objetos;
• Essa estrutura é chamada de Document Object Model - DOM;
• Cada elemento do documento HTML torna-se um objeto: atributos e textos;
• O JavaScript pode acessar cada objeto independentemente.
2
Árvore DOM
3
documento
html
head body
titleh1 p
a a a
4
Árvore DOM
Nó• Para criar o DOM de um documento, cada
elemento do HTML é conhecido como nó;
• O nó de elemento é distinguido pelo nome do elemento: head, body, h1…;
• Os elementos não são sempre únicos, então é possível identificar pelo atributo id;
• Nó de documento: início da árvore;
5
Tipos de Nós• Nós de elemento: são um tipo de nó e definem a
maior parte da estrutura do DOM;
• O conteúdo real de um documento está contido em dois outros tipos de nós:
• Nós de texto;
• Nós de atributos.
6
Nós de Texto• Tudo que não estiver entre <>…<>, é um nó de
texto no DOM;
• Nós de texto não tem filhos;
• Espaço em branco pode produzir nós de texto.
• Como mostra a figura a seguir…
7
8
documento
html
head body
title
texto
h1 p
texto texto a
texto
texto a texto a
texto
texto
Nós de Atributo• Se as tags e texto estão cobertos pelos nós de
elemento e de texto, faltam os atributos;
• Por mais que eles façam parte dos elementos, os atributos têm seus próprios nós;
• Os nós de atributos estão sempre ligados a um nó de elemento, mas não são nós de elemento ou de texto, dentro do DOM;
• Como mostra a figura a seguir…
9
10
a
texto
href
rel
Nós de Atributo
Exemplo da árvore DOM<!DOCTYPE html>
<html>
<head>
<title>Título da página</title>
</head>
<body>
<h1> Parágrafo 1 da página <h1>
<p>Parágrafo 1 da página <em>pedaço do text node com elemento em</em> volta para o elemento parágrafo</p>
<p>Parágrafo 2 da página</p>
</body>
</html>
11
Acessando os Nós• Manipular elementos por meio do DOM é parecido
com aplicar estilos de documento por meio de CSS:
• Especificar o elemento (ou grupo);
• Especificar o efeito a ser aplicado.
12
Localizando um elemento pelo "id"
• Para acessar um elemento pelo id em JS, utilize o método:
• getElementById(“string_com_id”);
• Esse método está disponível no nó elemento document;
• Ex.: var objeto = document.getElementById(“identificador”);
13
getElementById
14
var objeto = document.getElementById(“identificador”);
if (objeto != NULL){
alert(objeto.NodeName);{
Localizando elementos pelo nome da tag getElementsByTagName
var lista = document.getElementsByTagName(“li”);
var segundo_elemento = lista[1];
var numItens = lista.length;
for(i=0;i<lista.length;i++)
alert(lista[i].nodeName);
15
<!DOCTYPE html> <html> <head> <script> function getElements() {
var x=document.getElementsByTagName("input"); alert("Resposta = "+x.length);
} </script> </head> <body> Nome: <input type="text" size="20"></input><br/> Endereço: <input type="text" size="20"></input><br/>Telefone: <input type="text" size="20"></input><br/><br/> <input type="button" onclick="getElements()" value="Clique e veja quantos elementos inputs estão nessa página"/> </body> </html>
16
innerHTML• Exemplo:
function adicionaItem(nome){ document.getElementById('lista').innerHTML += '<li>'+nome+'</li>'}
17
<form name="formulario" method="post" action=""> <p> <label for="nome">Nome</label> <input type="text" name="nome" id="nome"/> </p></form><div id="id_div">Texto qualquer</div><ul>
<li>Primeiro valor</li><li>Segundo valor</li> <li>Terceiro valor</li>
<li>Quarto valor</li></ul><button onClick="caixa_texto()">Valor caixa de texto</button><button onClick="lista()">Valor da lista</button><script>function caixa_texto(){
var nome = document.getElementById("nome").value;document.getElementById("id_div").innerHTML = nome;
}function lista(){
var lista_itens = document.getElementsByTagName("li");document.getElementById("id_div").innerHTML += " - " +
lista_itens.length;}</script>
18
Restringir seleção de nome de Tag
• Se tiver 2 listas (ul) em um código, e apenas a 2ª lista interessar:
var lista = document.getElementsByTagName("ul");
var segundaLista = lista[1];
var itensSegundaLista = segundaLista.getElementsByTagName("li");
19
Localizando pelo nome da classe
destaques = document.getElementsByClassName("destaque");
• E isso retornará todos os elementos do HTML que possuem a classe "destaque".
20
ZEBRAR Tabela querySelectorAll()
<!DOCTYPE html><html lang="pt-BR"><head><meta charset="UTF-8" /><title>Zebra</title><style> .zebraon{background:silver}</style><script>window.onload=function(){ var zebrar=document.querySelectorAll('.zebra tbody tr') for(var i=0;i<zebrar.length;i+=2) zebrar[i].className='zebraon'}</script></head><body><table class="zebra"> <thead><tr> <th>Vendedor</th> <th>Total</th> </tr></thead> <tbody><tr> <td>Manoel</td> <td>12.300,00</td> </tr><tr> <td>Joaquim</td> <td>21.300,00</td> </tr><tr> <td>Maria</td> <td>13.200,00</td> </tr><tr> <td>Marta</td> <td>32.100,00</td> </tr><tr> <td>Antonio</td> <td>23.100,00</td> </tr><tr> <td>Pedro</td> <td>31.200,00</td> </tr></tbody></table></body></html> 21
document. querySelector()<div id="outerdiv" ><div id="innerdiv" ></div></div><script type="text/javascript">if (document.querySelector){ var outerdiv=document.querySelector(‘#outerdiv'); outerdiv.onmouseover=function(){ this.querySelector(‘#innerdiv’).style.background="yellow"; } outerdiv.onmouseout=function(){ this.querySelector(‘#innerdiv').style.background="silver"; }}</script>
<style>#outerdiv{
padding:50px; width:100px; height:100px; border:1px solid black;
}#innerdiv{
width:100%; height:100%; border:1px solid black; background:silver;
}</style>
<body><h1>A H1 element</h1><h2>A H2 element</h2><div>A DIV element</div><p>A p element.</p><p>A p element with a <span style = "color: brown;">span</span> element inside.</p><button onclick="myFunction()">Try it</button><script>function myFunction() { var x = document.querySelectorAll("h2, div, span"); var i; for (i = 0; i < x.length; i++) x[i].style.backgroundColor = "red";}</script></body>
Selecionar elementos com querySelectorAll
23
Outro exemplo…<form id="myform"><strong>Your hobbies:</strong><input name="hobbies" type="checkbox" value="movies" /> Movies <input name="hobbies" type="checkbox" value = "sports" />Sports <input name="hobbies" type="checkbox" value = "reading" />Reading <input name="hobbies" type="checkbox" value="sleeping" />Sleeping <br /><input type="submit" /></form><script type="text/javascript">if (document.querySelector){ document.querySelector('#myform').onsubmit=function(){ var checkedhobbies = this.querySelectorAll ('input[name = "hobbies"]:checked') for (var i=0; i<checkedhobbies.length; i++){ alert(checkedhobbies[i].value) } return false }}</script> 24
Hierarquia do elemento “div”<html> <head> <title>Hierarquia do elemento div por JavaScript</title> <script type="text/JavaScript"> function listarAtributos(){
var elem = document.getElementById("conta"); var atributos = ""; for(var i = 0; i < elem.attributes.length; i++)
atributos += elem.attributes[i].nodeName + "<br>"; elem.innerHTML = atributos;
} </script> </head> <body> <div id="conta" style="border: 1px solid red">Aqui é um elemento DIV</div> <button onclick="JavaScript:listarAtributos()">Listar atributos da DIV</button> </body> </html>
25
Exemplo temporizador
<!DOCTYPE html><html lang="pt-BR"><head><meta charset="UTF-8" /> <title>Notifier</title> <script type="text/javascript"> function notify(text){ document.getElementById("msg").innerHTML += "<p>" + text + "</p>"; titleFlick(); } function titleFlick(){ if(document.hasFocus()){ document.title='Notifier' return } document.title=document.title=='Notifier'?'* Notifier':'Notifier' setTimeout('titleFlick()',500) } </script></head><body> <input type="button" id="notify" value="Notificação em 5 segundos" onclick="notify('Você será notificado em 5 segundos…');setTimeout('notify(\'Ok!!!\')',5000)" /> <div id="msg"></div></body></html>
26
Exemplo usando getElementById()<!DOCTYPE html>
<html><head> <title>getElementById example</title> <script> function changeColor(newColor) { var elem = document.getElementById("para1"); elem.style.color = newColor; } </script></head><body> <p id="para1">Some text here</p> <button onclick="changeColor('blue');">blue</button> <button onclick="changeColor('red');">red</button></body></html>
27
Número de âncoras no texto
<!DOCTYPE html><html><body>
<a name="html">HTML Tutorial</a><br><a name="css">CSS Tutorial</a><br><a name="xml">XML Tutorial</a><br>
<p id="demo"></p>
<script>document.getElementById("demo").innerHTML ="Number of anchors are: " + document.anchors.length;</script>
</body></html>
28
<!DOCTYPE html><html><body>
<a name="html">HTML Tutorial</a><br><a name="css">CSS Tutorial</a><br><a name="xml">XML Tutorial</a><br>
<p>Click the button to display the innerHTML of the first anchor in the document.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>function myFunction() { document.getElementById("demo").innerHTML = document.anchors[0].innerHTML;}</script>
</body></html>
links
<!DOCTYPE html><html><body>
<p><a href="/html/default.asp">HTML</a><br><a href="/css/default.asp">CSS</a></p>
<p id="demo"></p>
<script>document.getElementById("demo").innerHTML ="Number of links: " + document.links.length;</script>
</body></html>
29
<!DOCTYPE html><html><body>
<p><a href="/html/default.asp">HTML</a><br><a href="/css/default.asp">CSS</a></p>
<p id="demo"></p>
<script>document.getElementById("demo").innerHTML ="The href of the first link is " + document.links[0].href;</script>
</body></html>
formulários
<!DOCTYPE html><html><body>
<form action="">First name: <input type="text" name="fname" value="Donald"><input type="submit" value="Submit"></form>
<p id="demo"></p>
<script>document.getElementById("demo").innerHTML ="Number of forms: " + document.forms.length;</script>
</body></html>
30
<!DOCTYPE html><html><body>
<form name="Form1"></form><form name="Form2"></form><form name="Form3"></form>
<p id="demo"></p>
<script>document.getElementById("demo").innerHTML ="The name of the first for is " + document.forms[0].name;</script>
</body></html>
imagens
<!DOCTYPE html><html><body>
<img src="pic_htmltree.gif"><img src="pic_navigate.gif">
<p id="demo"></p>
<script>document.getElementById("demo").innerHTML ="Number of images: " + document.images.length;</script>
</body></html>
31
<!DOCTYPE html><html><body>
<img id="img1" src="pic_htmltree.gif"><img id="img2" src="pic_navigate.gif">
<p id="demo"></p>
<script>document.getElementById("demo").innerHTML ="The id of the first image is " + document.images[0].id;</script>
</body></html>
CSS
<!DOCTYPE html><html><body>
<img id="img1" src="pic_htmltree.gif"><img id="img2" src="pic_navigate.gif">
<p id="demo"></p>
<script>document.getElementById("demo").innerHTML ="The id of the first image is " + document.images[0].id;</script>
</body></html>
32
<!DOCTYPE html><html><head><script>function bgChange(bg) { document.body.style.background = bg;}</script></head><body><h2>Change background color</h2><p>Mouse over the squares!</p><table style="width:300px;height:100px"> <tr> <td onmouseover="bgChange(this.style.backgroundColor)" onmouseout="bgChange('transparent')" style="background-color:Khaki"> </td> <td onmouseover="bgChange(this.style.backgroundColor)" onmouseout="bgChange('transparent')" style="background-color:PaleGreen"> </td> <td onmouseover="bgChange(this.style.backgroundColor)" onmouseout="bgChange('transparent')" style="background-color:Silver"> </td> </tr></table></body></html>
Métodos usados para percorrer o documento
• hasChildNodes - retorna true se o elemento possui filhos;• firstChild - retorna uma referência ao primeiro elemento filho;• lastChild - retorna uma referência ao último elemento filho;• nextSibling - retorna uma referência ao irmão posterior ao elemento;• previousSibling - retorna uma referência ao irmão anterior ao elemento;• nodeName - retorna o nome da TAG do elemento (apenas para
elementos nó);• nodeValue - retorna o valor do elemento (apenas para elementos texto);• nodeType - retorna o tipo do elemento;• parentNode - retorna uma referência ao elemento pai.
Essas propriedades são a chave para ser capaz de manipular a árvore de documentos para acessar dados específicos do nó.
33
Método DOM hasChildNodes()
<!DOCTYPE html><html><body><ul id="myList"> <li>Café</li> <li>Leite</li></ul><p>Click the button to see if the ul element has any child nodes.</p><button onclick="myFunction()">Try it</button><p id="demo"></p><script>function myFunction() { var list = document.getElementById("myList").hasChildNodes(); document.getElementById("demo").innerHTML = list;}</script></body></html>
34
Note: Whitespace inside elements is considered as text, and text is considered as nodes.
HTML DOM Propriedade
firstChild/lastChild
<!DOCTYPE html><html><body><p>Example list:</p><ul id="myList"><li>Coffee</li>
<li>Tea</li><li>Cookies</li></ul>
<button onclick="myFunction()">Try it</button><p id="demo"></p><script>function myFunction() { var list = document.getElementById("myList").firstChild.innerHTML;document.getElementById("demo").innerHTML = list;}</script></body></html>
35
If you add whitespace before the first LI element, the result will be "undefined".
HTML DOM Propriedade parentNode
<!DOCTYPE html> <html> <body>
<p>Example list:</p> <ul>
<li id="myLI">Coffee</li> <li>Tea</li>
</ul> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script>
function myFunction() { var x = document.getElementById("myLI").parentNode.nodeName; document.getElementById("demo").innerHTML = x; }
</script> </body> </html>
36
Click the button to get the node name of the parent node of the li element in the list.
<!DOCTYPE html><html><head></head><body>
<div> <span onclick="this.parentNode.style.display = 'none';" class="closebtn">×</span> <p>To close this container, click on the X symbol to the right.</p></div>
</body></html>
37
<style>div { box-sizing: border-box; padding: 16px; width: 100%; background-color: red; color: #fff;}.closebtn { float: right; font-size: 30px; font-weight: bold; cursor: pointer;}.closebtn:hover { color: #000;}</style>
HTML DOM Propriedade parentNode
HTML DOM Propriedade nextSibling
<!DOCTYPE html><html><body><p>Example list:</p><ul><li id="item1">Coffee (first li)</li><li id="item2">Tea (second li)</li>
</ul><button onclick="myFunction()">Try it</button><p id="demo"></p>
<script>function myFunction() { var x = document.getElementById("item1").nextSibling.innerHTML; document.getElementById("demo").innerHTML = x;}</script></body></html>
38
Click the button to get the HTML content of the next sibling of the first list item.
previousSibling
Método DOM removeChild()
<!DOCTYPE html><html><body><ul id="myList">
<li>Coffee</li><li>Tea</li>
</ul><button onclick="myFunction()">Try it</button><script>function myFunction() { var list = document.getElementById("myList"); if (list.hasChildNodes()) list.removeChild(list.childNodes[0]);}</script>
39
Criar um novo elemento e adicioná-lo à árvore do documento<html> <head> <script> // run this function when the document is loaded window.onload = function() { // create a couple of elements // in an otherwise empty HTML page heading = document.createElement("h1"); heading_text = document.createTextNode("Big Head!"); heading.appendChild(heading_text); document.body.appendChild(heading); } </script> </head> <body> </body></html>
40