SlideShare uma empresa Scribd logo
1 de 40
Baixar para ler offline
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
title
h1 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").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>
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>
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>
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>
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">&times;</
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

Mais conteúdo relacionado

Mais procurados

Minicurso de JavaScript (Portuguese)
Minicurso de JavaScript (Portuguese)Minicurso de JavaScript (Portuguese)
Minicurso de JavaScript (Portuguese)Bruno Grange
 
Introdução Ao Web Design
Introdução Ao Web DesignIntrodução Ao Web Design
Introdução Ao Web DesignSandra Oliveira
 
Aula 2 – Introdução a HTML - conceitos básicos e estrutura
Aula 2 – Introdução a HTML - conceitos básicos e estruturaAula 2 – Introdução a HTML - conceitos básicos e estrutura
Aula 2 – Introdução a HTML - conceitos básicos e estruturaAndré Constantino da Silva
 
Introdução ao Web Design: Aula 1 - Imersão ao Web Design
Introdução ao Web Design: Aula 1 - Imersão ao Web DesignIntrodução ao Web Design: Aula 1 - Imersão ao Web Design
Introdução ao Web Design: Aula 1 - Imersão ao Web DesignGustavo Zimmermann
 
Documentação de Arquitetura de Software Aplicando o C4 Model
Documentação de Arquitetura  de Software Aplicando o C4 ModelDocumentação de Arquitetura  de Software Aplicando o C4 Model
Documentação de Arquitetura de Software Aplicando o C4 ModelDouglas Alonso
 
tmn - Introdução ao JavaScript
tmn - Introdução ao JavaScripttmn - Introdução ao JavaScript
tmn - Introdução ao JavaScriptClaudio Gamboa
 
Introdução à Criação De Páginas Web Aula1
Introdução à Criação De Páginas Web Aula1Introdução à Criação De Páginas Web Aula1
Introdução à Criação De Páginas Web Aula1marioreis
 
Internet das Coisas: Conceitos e Aplicações
Internet das Coisas: Conceitos e AplicaçõesInternet das Coisas: Conceitos e Aplicações
Internet das Coisas: Conceitos e AplicaçõesFaculdade Martha Falcão
 
Linguagem de Programação Python
Linguagem de Programação PythonLinguagem de Programação Python
Linguagem de Programação PythonJunior Sobrenome
 

Mais procurados (20)

Minicurso de JavaScript (Portuguese)
Minicurso de JavaScript (Portuguese)Minicurso de JavaScript (Portuguese)
Minicurso de JavaScript (Portuguese)
 
Html
HtmlHtml
Html
 
Introdução Ao Web Design
Introdução Ao Web DesignIntrodução Ao Web Design
Introdução Ao Web Design
 
Aula 2 – Introdução a HTML - conceitos básicos e estrutura
Aula 2 – Introdução a HTML - conceitos básicos e estruturaAula 2 – Introdução a HTML - conceitos básicos e estrutura
Aula 2 – Introdução a HTML - conceitos básicos e estrutura
 
Introdução ao Web Design: Aula 1 - Imersão ao Web Design
Introdução ao Web Design: Aula 1 - Imersão ao Web DesignIntrodução ao Web Design: Aula 1 - Imersão ao Web Design
Introdução ao Web Design: Aula 1 - Imersão ao Web Design
 
Tutorial Desenvolvendo Pong no Unity 3D - Victory Island Studios
Tutorial Desenvolvendo Pong no Unity 3D - Victory Island StudiosTutorial Desenvolvendo Pong no Unity 3D - Victory Island Studios
Tutorial Desenvolvendo Pong no Unity 3D - Victory Island Studios
 
Documentação de Arquitetura de Software Aplicando o C4 Model
Documentação de Arquitetura  de Software Aplicando o C4 ModelDocumentação de Arquitetura  de Software Aplicando o C4 Model
Documentação de Arquitetura de Software Aplicando o C4 Model
 
Curso de Desenvolvimento Web - Módulo 02 - CSS
Curso de Desenvolvimento Web - Módulo 02 - CSSCurso de Desenvolvimento Web - Módulo 02 - CSS
Curso de Desenvolvimento Web - Módulo 02 - CSS
 
Web Design > Aula 00
Web Design > Aula 00Web Design > Aula 00
Web Design > Aula 00
 
Aula03 - JavaScript
Aula03 - JavaScriptAula03 - JavaScript
Aula03 - JavaScript
 
ECDL
ECDLECDL
ECDL
 
Aula 00 - Introducao ao Windows Server .pdf
Aula 00 - Introducao ao Windows Server .pdfAula 00 - Introducao ao Windows Server .pdf
Aula 00 - Introducao ao Windows Server .pdf
 
tmn - Introdução ao JavaScript
tmn - Introdução ao JavaScripttmn - Introdução ao JavaScript
tmn - Introdução ao JavaScript
 
Introdução à Criação De Páginas Web Aula1
Introdução à Criação De Páginas Web Aula1Introdução à Criação De Páginas Web Aula1
Introdução à Criação De Páginas Web Aula1
 
Modelo TCP/IP
Modelo TCP/IPModelo TCP/IP
Modelo TCP/IP
 
Curso de Desenvolvimento Web - Módulo 01 - HTML
Curso de Desenvolvimento Web - Módulo 01 - HTMLCurso de Desenvolvimento Web - Módulo 01 - HTML
Curso de Desenvolvimento Web - Módulo 01 - HTML
 
Html Básico
Html BásicoHtml Básico
Html Básico
 
Internet das Coisas: Conceitos e Aplicações
Internet das Coisas: Conceitos e AplicaçõesInternet das Coisas: Conceitos e Aplicações
Internet das Coisas: Conceitos e Aplicações
 
Introdução a React Native
Introdução a React NativeIntrodução a React Native
Introdução a React Native
 
Linguagem de Programação Python
Linguagem de Programação PythonLinguagem de Programação Python
Linguagem de Programação Python
 

Destaque

Aula 03-oac-componentes-de-um-sistema-de-computacao
Aula 03-oac-componentes-de-um-sistema-de-computacaoAula 03-oac-componentes-de-um-sistema-de-computacao
Aula 03-oac-componentes-de-um-sistema-de-computacaoCristiano Pires Martins
 

Destaque (20)

Java script aula 09 - JQuery
Java script   aula 09 - JQueryJava script   aula 09 - JQuery
Java script aula 09 - JQuery
 
Java script aula 04 - objeto array
Java script   aula 04 - objeto arrayJava script   aula 04 - objeto array
Java script aula 04 - objeto array
 
Java script aula 07 - eventos
Java script   aula 07 - eventosJava script   aula 07 - eventos
Java script aula 07 - eventos
 
Java script aula 03 - objetos
Java script   aula 03 - objetosJava script   aula 03 - objetos
Java script aula 03 - objetos
 
Java script aula 05 - funções
Java script   aula 05 - funçõesJava script   aula 05 - funções
Java script aula 05 - funções
 
Java script aula 02 - operadores
Java script   aula 02 - operadoresJava script   aula 02 - operadores
Java script aula 02 - operadores
 
Java script aula 10 - angularjs
Java script   aula 10 - angularjsJava script   aula 10 - angularjs
Java script aula 10 - angularjs
 
Java script aula 08 - formulários
Java script   aula 08 - formuláriosJava script   aula 08 - formulários
Java script aula 08 - formulários
 
Java script - funções
Java script - funçõesJava script - funções
Java script - funções
 
Javascript aula 01 - visão geral
Javascript   aula 01 - visão geralJavascript   aula 01 - visão geral
Javascript aula 01 - visão geral
 
Java script aula 07 - j-query
Java script   aula 07 - j-queryJava script   aula 07 - j-query
Java script aula 07 - j-query
 
Aula 06 textos na web
Aula 06   textos na webAula 06   textos na web
Aula 06 textos na web
 
Aula 07 acessibilidade
Aula 07  acessibilidadeAula 07  acessibilidade
Aula 07 acessibilidade
 
Aula 05 layout e composição do site
Aula 05   layout e composição do siteAula 05   layout e composição do site
Aula 05 layout e composição do site
 
Aula 03-oac-componentes-de-um-sistema-de-computacao
Aula 03-oac-componentes-de-um-sistema-de-computacaoAula 03-oac-componentes-de-um-sistema-de-computacao
Aula 03-oac-componentes-de-um-sistema-de-computacao
 
Aula 07 - lista linear
Aula 07 - lista linearAula 07 - lista linear
Aula 07 - lista linear
 
Aula 08 - árvores
Aula 08 - árvoresAula 08 - árvores
Aula 08 - árvores
 
OAC Aula 09 - Entrada e Saída
OAC Aula 09 - Entrada e SaídaOAC Aula 09 - Entrada e Saída
OAC Aula 09 - Entrada e Saída
 
Aula 02 semiótica e cores
Aula 02   semiótica e coresAula 02   semiótica e cores
Aula 02 semiótica e cores
 
Aula 04 layout e composição do site
Aula 04   layout e composição do siteAula 04   layout e composição do site
Aula 04 layout e composição do site
 

Semelhante a DOM - Acessando elementos HTML com JavaScript

Semelhante a DOM - Acessando elementos HTML com JavaScript (20)

jQuery na Prática!
jQuery na Prática!jQuery na Prática!
jQuery na Prática!
 
Programação Web com jQuery
Programação Web com jQueryProgramação Web com jQuery
Programação Web com jQuery
 
Programação Web com jQuery
Programação Web com jQueryProgramação Web com jQuery
Programação Web com jQuery
 
Minicurso HTML
Minicurso HTMLMinicurso HTML
Minicurso HTML
 
HTML & CSS - Aula 2
HTML & CSS - Aula 2HTML & CSS - Aula 2
HTML & CSS - Aula 2
 
Javascript para CSharpers - Append B - jQuery
Javascript para CSharpers - Append B - jQueryJavascript para CSharpers - Append B - jQuery
Javascript para CSharpers - Append B - jQuery
 
XHTML Básico
XHTML BásicoXHTML Básico
XHTML Básico
 
Construindo temas para Plone com Diazo
Construindo temas para Plone com DiazoConstruindo temas para Plone com Diazo
Construindo temas para Plone com Diazo
 
Bloco 5.1 - Manipulação do DOM
Bloco 5.1 - Manipulação do DOMBloco 5.1 - Manipulação do DOM
Bloco 5.1 - Manipulação do DOM
 
Programacao para Web I 03 HTML
Programacao para Web I 03 HTMLProgramacao para Web I 03 HTML
Programacao para Web I 03 HTML
 
HTML + CSS
HTML + CSSHTML + CSS
HTML + CSS
 
HTML & CSS - Aula 3
HTML & CSS - Aula 3 HTML & CSS - Aula 3
HTML & CSS - Aula 3
 
Linguagem html
Linguagem htmlLinguagem html
Linguagem html
 
jQuery - A biblioteca javascript
jQuery - A biblioteca javascriptjQuery - A biblioteca javascript
jQuery - A biblioteca javascript
 
html css js ajax exercícios de programação
html css js ajax exercícios de programaçãohtml css js ajax exercícios de programação
html css js ajax exercícios de programação
 
Html 20.10
Html   20.10Html   20.10
Html 20.10
 
Iniciação em HTML
Iniciação em HTMLIniciação em HTML
Iniciação em HTML
 
Curso de XHTML
Curso de XHTMLCurso de XHTML
Curso de XHTML
 
HTML - HyperText Markup Language - 2
HTML - HyperText Markup Language - 2HTML - HyperText Markup Language - 2
HTML - HyperText Markup Language - 2
 
Introdução ao HTML e CSS
Introdução ao HTML e CSSIntrodução ao HTML e CSS
Introdução ao HTML e CSS
 

Mais de Cristiano Pires Martins (14)

Aula 08 - árvores
Aula 08 - árvoresAula 08 - árvores
Aula 08 - árvores
 
Aula 01 introdução
Aula 01   introduçãoAula 01   introdução
Aula 01 introdução
 
Aula 03 esquema de cores
Aula 03   esquema de coresAula 03   esquema de cores
Aula 03 esquema de cores
 
WDI - aula 07 - css com html
WDI - aula 07 - css com htmlWDI - aula 07 - css com html
WDI - aula 07 - css com html
 
Aula 08-oac-execucao-de-programas
Aula 08-oac-execucao-de-programasAula 08-oac-execucao-de-programas
Aula 08-oac-execucao-de-programas
 
Aula 07-oac-processadores
Aula 07-oac-processadoresAula 07-oac-processadores
Aula 07-oac-processadores
 
Aula 06-oac-memoria-principal
Aula 06-oac-memoria-principalAula 06-oac-memoria-principal
Aula 06-oac-memoria-principal
 
Aula 05-oac-conceitos-de-logica-digital
Aula 05-oac-conceitos-de-logica-digitalAula 05-oac-conceitos-de-logica-digital
Aula 05-oac-conceitos-de-logica-digital
 
Aula 02-oac-historia-da-computacao-part2
Aula 02-oac-historia-da-computacao-part2Aula 02-oac-historia-da-computacao-part2
Aula 02-oac-historia-da-computacao-part2
 
Aula 02-oac-historia-da-computacao-part1
Aula 02-oac-historia-da-computacao-part1Aula 02-oac-historia-da-computacao-part1
Aula 02-oac-historia-da-computacao-part1
 
Aula 01-oac-introducao-a-oac
Aula 01-oac-introducao-a-oacAula 01-oac-introducao-a-oac
Aula 01-oac-introducao-a-oac
 
Aula 10-oac-arquitetura-risc
Aula 10-oac-arquitetura-riscAula 10-oac-arquitetura-risc
Aula 10-oac-arquitetura-risc
 
Aula 06-sistemas de-arquivo
Aula 06-sistemas de-arquivoAula 06-sistemas de-arquivo
Aula 06-sistemas de-arquivo
 
Aula 04-gerenciamento-basico-de-memoria
Aula 04-gerenciamento-basico-de-memoriaAula 04-gerenciamento-basico-de-memoria
Aula 04-gerenciamento-basico-de-memoria
 

DOM - Acessando elementos HTML com JavaScript

  • 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
  • 8. 8 documento html head body title texto h1 p texto texto a texto texto a texto a texto texto
  • 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
  • 21. 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
  • 22. 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>
  • 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
  • 26. 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
  • 27. 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
  • 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">&times;</ 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