1. 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
2. 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
5. 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
6. 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
7. 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
9. 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
11. 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
12. 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
13. 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
14. getElementById
14
var objeto = document.getElementById(“identificador”);
if (objeto != NULL)
{
alert(objeto.NodeName);
{
15. 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
16. <!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
18. <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
19. 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
20. Localizando pelo nome da
classe
destaques = document.getElementsByClassName("destaque");
• E isso retornará todos os elementos do HTML que possuem a
classe "destaque".
20
23. <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
24. 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
25. 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
28. 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").inn
erHTML =
"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>
29. 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").inne
rHTML =
"The href of the first link is " +
document.links[0].href;
</script>
</body>
</html>
30. 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").inner
HTML =
"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").i
nnerHTML =
"The name of the first for is " +
document.forms[0].name;
</script>
</body>
</html>
31. 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").in
nerHTML =
"The id of the first image is " +
document.images[0].id;
</script>
</body>
</html>
32. 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>
33. 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
34. 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.
35. 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".
36. 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.
37. <!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
38. 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
39. 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
40. 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