document object model (dom) programação na internet secção de sistemas e tecnologias de...
TRANSCRIPT
Document Object Model
(DOM)
Programação na Internet Secção de Sistemas e Tecnologias de Informação
ISEL-DEETC-LEICLuis Falcão - [email protected]
Carlos Guedes – [email protected] Datia – [email protected]
2008 - 2009©ISEL/DEETC/STI – Programação na Internet
Autores e contributos• Autores
– Luís Falcão
• Contributos– Paulo Pereira– Pedro Félix– Jorge Martins– Carlos Guedes– Nuno Datia
22DOM: Document Object Model
2008 - 2009©ISEL/DEETC/STI – Programação na Internet
DOM – Introdução• API para acesso aos elementos de um documento HTML e XML, bem
formado (well-formed).• Define a estrutura lógica dos documentos e a forma de acesso e
manipulação.• O DOM permite:
– Criar documentos– Navegar através da sua estrutura– Adicionar, remover e modificar elementos e o seu conteúdo– Aceder a todo (com algumas excepções, por enquanto) o conteúdo de um
documento (HTML e XML)
• A especificação DOM define uma interface independente de qualquer linguagem e plataforma (definida em IDL da OMG, definido no CORBA 2.2).
• URL da especificação DOM: http://www.w3.org/DOM/
3DOM: Document Object Model
2008 - 2009©ISEL/DEETC/STI – Programação na Internet
Características básicas do DOM1. O modelo de objectos é independente de qualquer linguagem e plataforma.2. Existência de uma interface base no DOM que é aplicável a documentos HTML, CSS
e XML.3. O modelo de objectos pode ser utilizado para construir e destruir um documento.4. Não exclui a possibilidade de utilização do modelo de objectos por agentes
externos ao documento, ou a script embebido no documento.5. Utilização de convenções de nomes entre os vários níveis de DOM.6. Uma implementação DOM não necessita de criar componentes visuais.7. Os objectos específicos para documentos HTML, CSS e XML são definidos pelos
elementos dessas linguagens.8. Permitir ler um documento e criar outro com a mesma estrutura.9. Não expõe o utilizador a problemas relacionados com segurança, validade, ou
privacidade.10. Não exclui a possibilidade de existência de outros mecanismos para manipular os
documentos.
4DOM: Document Object Model
2008 - 2009©ISEL/DEETC/STI – Programação na Internet
Níveis de DOM• Actividades iniciadas em Agosto de 1997.• A especificação DOM foi dividida em vários níveis (actualmente 3). Cada
nível trata de um conjunto de funcionalidades.– Os níveis 1, 2 e 3 já são recomendações.
• O DOM Working Group não é o único do W3C que produz APIs e extensões à arquitectura DOM. Outros módulos do DOM incluem:– DOM para MathML 2.0: API genérica para documentos MathML 2.0.– DOM para animações SMIL (Synchronized Multimedia Integration Language):
API genérica para animações SMIL. – DOM para SVG 1.0: API genérica para documentos SVG 1.0.
5DOM: Document Object Model
2008 - 2009©ISEL/DEETC/STI – Programação na Internet
Arquitectura DOM• A arquitectura do DOM está dividida em módulos.• Cada módulo endereça um domínio específico.• Os domínios cobertos “actualmente” pela API DOM são:
– DOM Core
– DOM XML
– DOM HTML
– DOM Events
– DOM CSS
– DOM Load and Save
– DOM Validation
– DOM XPath
6DOM: Document Object Model
2008 - 2009©ISEL/DEETC/STI – Programação na Internet
DOM Nível 1• DOM Nível1 (especificação desde Outubro de 1998)
– Navegação sobre a estrutura do documento– Manipulação do documento– Manipulação do conteúdo
7DOM: Document Object Model
2008 - 2009©ISEL/DEETC/STI – Programação na Internet
DOM Nível 2• DOM Nível2 (recomendação desde Novembro de 2000)
– Extensões ao nível 1 para suportar XML 1.0 Namespaces (Document Object Model Level 2 Core )
– Modelo de objectos para as Cascading StyleSheets (Document Object Model Level 2 Style)
– Modelo de eventos para user interfaces e de manipulação do documento(Document Object Model Level 2 Events)
– Possibilidade de ter visão linear e filtrada um documento (Document Object Model Level 2 Traversal and Range)
– Especificação baseada no DOM Nível 2 Core e não compatível com a DOM Nível 1 HTML (Document Object Model Level 2 HTML)
– Manipulação do aspecto visual de um documento (Document Object Model Level 2 Views)
8DOM: Document Object Model
2008 - 2009©ISEL/DEETC/STI – Programação na Internet
DOM Nível 2 - Arquitectura
9
2008 - 2009©ISEL/DEETC/STI – Programação na Internet
DOM Nível 3• DOM Nível3 (já é uma recomendação)
– Extensões ao nível 2 para suporte total dos Namespaces XML 1.0– (Document Object Model Level 3 Core)– Load and Save– (Document Object Model Level 3 Load and Save)– Validações– (Document Object Model Level 3 Validation)– Eventos– (Document Object Model Level 3 Events)– XPath– (Document Object Model Level 3 XPath)
10DOM: Document Object Model
2008 - 2009©ISEL/DEETC/STI – Programação na Internet
DOM Nível 3 Arquitectura
11
2008 - 2009©ISEL/DEETC/STI – Programação na Internet
DOM Nível 3 Arquitectura (final)
12
2008 - 2009©ISEL/DEETC/STI – Programação na Internet
DOM – O que é?• API para acesso ao conteúdo de um documento.• Estrutura de objectos que espelha a estrutura do documento original. • O modelo de objectos DOM define:
– As interfaces e os objectos utilizados para representar os elementos de um documento.– A semântica dessas interfaces.– As relações e colaborações entre interfaces e objectos.
13
<TABLE> <TBODY> <TR> <TD>Shady Grove</TD> <TD>Aeolian</TD> </TR> <TR> <TD>Over the River, Charlie</TD> <TD>Dorian</TD> </TR> </TBODY></TABLE>
DOM: Document Object Model
2008 - 2009©ISEL/DEETC/STI – Programação na Internet
DOM – O que não é?• Embora fortemente influenciado pelo “Dynamic HTML Object Model”
(DOM Nível 0), não implementa toda a sua funcionalidade no Nível 1.• Não é uma especificação binária (tipo COM ou CORBA). Tem que ser feita
uma adaptação (mapeamento) para cada linguagem.• Não define como é que objectos são representados em XML ou HTML. Em
vez disso define como é que documentos HTML e XML são representados na forma de objectos.
• Não é um conjunto de estruturas de dados. É um modelo de objectos que define interfaces. A API define apenas relações lógicas entre interfaces, não sugerindo nenhuma estrutura física para a implementação.
• Não define qual a informação que é relevante num documento, nem como esta deve ser estruturada.
• Não é um competidor do COM ou CORBA. Pode ser implementado utilizando qualquer um destes sistemas de objectos (ou não).
14DOM: Document Object Model
2008 - 2009©ISEL/DEETC/STI – Programação na Internet
Tipos e interfaces Básicas (1)
15
typedef sequence<unsigned short> DOMString;
exception DOMException { unsigned short code;};// ExceptionCodeconst unsigned short INDEX_SIZE_ERR = 1;const unsigned short DOMSTRING_SIZE_ERR = 2;const unsigned short HIERARCHY_REQUEST_ERR = 3;const unsigned short WRONG_DOCUMENT_ERR = 4;const unsigned short INVALID_CHARACTER_ERR = 5;const unsigned short NO_DATA_ALLOWED_ERR = 6;const unsigned short NO_MODIFICATION_ALLOWED_ERR = 7;const unsigned short NOT_FOUND_ERR = 8;const unsigned short NOT_SUPPORTED_ERR = 9;const unsigned short INUSE_ATTRIBUTE_ERR = 10;
interface DOMImplementation {boolean hasFeature(in DOMString feature,in DOMString version);
};
interface DocumentFragment : Node {};
DOMString
DOMException
DOMImplementation
DOMFragment
DOM: Document Object Model
2008 - 2009©ISEL/DEETC/STI – Programação na Internet
Interface Document
16
interface Document : Node { // Attributes readonly attribute DocumentType doctype; readonly attribute DOMImplementation implementation; readonly attribute Element documentElement; // Methods Element createElement(in DOMString tagName) raises(DOMException); DocumentFragment createDocumentFragment(); Text createTextNode(in DOMString data); Comment createComment(in DOMString data); CDATASection createCDATASection(in DOMString data) raises(DOMException); ProcessingInstruction createProcessingInstruction (in DOMString target, in DOMString data) raises(DOMException); Attr createAttribute(in DOMString name) raises(DOMException); EntityReference createEntityReference (in DOMString name) raises(DOMException); Element getElementById(in DOMString idname);
// DOM Level 2 NodeList getElementsByTagName(in DOMString tagname);};
Node
DocumentDocument
2008 - 2009©ISEL/DEETC/STI – Programação na Internet
Interface Node - Constantes
17
interface Node {// Constants// NodeType const unsigned short ELEMENT_NODE = 1;const unsigned short ATTRIBUTE_NODE = 2;const unsigned short TEXT_NODE = 3;const unsigned short CDATA_SECTION_NODE = 4;const unsigned short ENTITY_REFERENCE_NODE = 5;const unsigned short ENTITY_NODE = 6;const unsigned short PROCESSING_INSTRUCTION_NODE = 7;const unsigned short COMMENT_NODE = 8;const unsigned short DOCUMENT_NODE = 9;const unsigned short DOCUMENT_TYPE_NODE = 10;const unsigned short DOCUMENT_FRAGMENT_NODE = 11;const unsigned short NOTATION_NODE = 12;...
};
Node
Node
2008 - 2009©ISEL/DEETC/STI – Programação na Internet
Interface Node - Atributos
18
interface Node { ... // Attributes readonly attribute unsigned short nodeType; readonly attribute Node parentNode; readonly attribute NodeList childNodes; readonly attribute Node firstChild; readonly attribute Node lastChild; readonly attribute Node previousSibling; readonly attribute Node nextSibling; readonly attribute Document ownerDocument; readonly attribute DOMString nodeName; attribute DOMString nodeValue; readonly attribute NamedNodeMap attributes;};
Valores de nodeName, nodeValue e attributes, consoante o tipo de elemento
Node
2008 - 2009©ISEL/DEETC/STI – Programação na Internet
Interface Node - Métodos
19
interface Node { ... // Methods Node insertBefore(in Node newChild, in Node refChild) raises(DOMException); Node replaceChild(in Node newChild, in Node oldChild) raises(DOMException); Node removeChild(in Node oldChild) raises(DOMException); Node appendChild(in Node newChild) raises(DOMException); boolean hasChildNodes(); Node cloneNode(in boolean deep) raises(DOMException);};
Node
2008 - 2009©ISEL/DEETC/STI – Programação na Internet
Interfaces NodeList e NamedNodeMap
20
interface NodeList {// Attributesreadonly attribute unsigned long length;
// MethodsNode item(in unsigned long index); //
x[index]};
interface NamedNodeMap {// Attributesreadonly attribute unsigned long length;
// MethodsNode getNamedItem(in DOMString name);Node setNamedItem(in Node arg)
raises(DOMException);Node removeNamedItem(in DOMString name)
raises(DOMException);Node item(in unsigned long index); // x[index]
};
NodeList
NamedNodeMap
2008 - 2009©ISEL/DEETC/STI – Programação na Internet
Interface Attr
21
interface Attr : Node {readonly attribute DOMString name;readonly attribute boolean specified;// Modified in DOM Level 1:attribute DOMString value;};
Node
Attr
Attr
2008 - 2009©ISEL/DEETC/STI – Programação na Internet
Interface Element
22
interface Element : Node {readonly attribute DOMString tagName;DOMString getAttribute(in DOMString name);void setAttribute(in DOMString name, in DOMString value)
raises(DOMException);void removeAttribute(in DOMString name) raises(DOMException);Attr getAttributeNode(in DOMString name);Attr setAttributeNode(in Attr newAttr) raises(DOMException);Attr removeAttributeNode(in Attr oldAttr) raises(DOMException);NodeList getElementsByTagName(in DOMString name); // * means all Tagsvoid normalize();
};
Node
ElementElement
2008 - 2009©ISEL/DEETC/STI – Programação na Internet
Interface CharacterData
23
interface CharacterData : Node {attribute DOMString data; // raises(DOMException) on setting and retrievalreadonly attribute unsigned long length;
DOMString substringData (in unsigned long offset, in unsigned long count) raises(DOMException);void appendData
(in DOMString arg) raises(DOMException);void insertData
(in unsigned long offset, in DOMString arg) raises(DOMException);void deleteData
(in unsigned long offset, in unsigned long count) raises(DOMException);void replaceData
(in unsigned long offset, in unsigned long count, in DOMString arg) raises(DOMException);};
Node
CharacterDataCharacterData
2008 - 2009©ISEL/DEETC/STI – Programação na Internet
Interfaces Text e Comment
24
interface Text : CharacterData {Text splitText(in unsigned long offset)
raises(DOMException);};
Text
Node
CharacterData
Comment
interface Comment : CharacterData {};
Text
Comment
2008 - 2009©ISEL/DEETC/STI – Programação na Internet
Interfaces DOM para HTML• Extensões às interfaces básicas DOM, específicas para documentos HTML.• Na interface básica, são disponibilizadas todas as funcionalidades que permitem:
– Manipulação da estrutura hierárquica dos documentos.– Manipulação de elementos.– Manipulação de atributos.
• Na interface DOM para HTML são disponibilizadas funcionalidades que dependem das especificidades dos elementos do HTML. Os objectivos desta API são:– Especialização de funcionalidades relacionadas com os elementos HTML.– Manutenção de compatibilidade com DOM Nível 0 (DHTML).– Oferecer mecanismos para implementar as operações mais frequentes sobre
documentos HTML (sempre que se justifique).
– Esta API não é obrigatória numa implementação DOM nível 1. Caso a implementação suporte estas interfaces, deve responder true no método hasFeature de DOMImplementation, quando recebe como parâmetros as strings “HTML” e “1.0”.
25DOM: Document Object Model
2008 - 2009©ISEL/DEETC/STI – Programação na Internet
Interface HTMLCollection
26
interface HTMLCollection {readonly attribute unsigned long length;Node item(in unsigned long index);// nodeName corresponds to HTML attribute “id” or “name”Node namedItem(in DOMString nodeName);
};
HTMLCollection
2008 - 2009©ISEL/DEETC/STI – Programação na Internet
Interface HTMLDocument
27
interface HTMLDocument : Document {attribute DOMString title;readonly attribute DOMString referrer;readonly attribute DOMString domain;readonly attribute DOMString URL;attribute HTMLElement body;readonly attribute HTMLCollection images;readonly attribute HTMLCollection applets;readonly attribute HTMLCollection links;readonly attribute HTMLCollection forms;readonly attribute HTMLCollection anchors;attribute DOMString cookie;
void open();void close();void write(in DOMString text);void writeln(in DOMString text);Element getElementById(in DOMString elementId);NodeList getElementsByName(in DOMString
elementName);};
Node
Document
HTMLDocument
HTMLDocument
2008 - 2009©ISEL/DEETC/STI – Programação na Internet
Interface HTMLElement
Elementos HTML que apenas disponibilizam a interface básica
HTMLElement:– HEAD
– special: SUB, SUP, SPAN, BDO
– font: TT, I, B, U, S, STRIKE, BIG, SMALL
– phrase: EM, STRONG, DFN, CODE, SAMP, KBD, VAR, CITE, ACRONYM, ABBR
– list: DD, DT
– NOFRAMES, NOSCRIPT
– ADDRESS, CENTER
28
interface HTMLElement : Element {attribute DOMString id;attribute DOMString title;attribute DOMString lang;attribute DOMString dir;attribute DOMString
className;};
Node
Element
HTMLElement
HTMLElement
DOM: Document Object Model
2008 - 2009©ISEL/DEETC/STI – Programação na Internet
Interfaces para outros elementos do HTML
29
Node
Element
HTMLElement
HTMLHtmlElement HTMLHeadElement
HTMLTitleElement
HTMLMetaElement
HTMLBaseElement HTMLStyleElement
HTMLBodyElement
HTMLFormElement
HTMLLinkElement
2008 - 2009©ISEL/DEETC/STI – Programação na Internet
DOM 2 – Modelo de Eventos• Sistema de eventos genérico que
– Permite o registo de handlers de eventos– Fornece conjuntos de eventos para a controlo da UI e para notificação da
alteração da estrutura do documento– Define a informação contextual para cada um dos tipos de eventos– Contém como subconjunto, os eventos utilizados no DOM nível 0
• Existem várias técnicas para gerir a captura de eventos• É possível a um evento ser capturado ao longo de um caminho na árvore
DOM
30DOM: Document Object Model
2008 - 2009©ISEL/DEETC/STI – Programação na Internet
Event Flow• Existem duas fases no processamento de eventos:
– Capture – A primeira das fases, onde o evento percorre a árvore do documento, desde a raiz até ao elemento a que é destinado o evento
– Bubble – Processo contrário, onde o evento depois de processado pelo elemento a que se destinava, é passado para o nó pai, afim de ser processado
31
Capture Bubbling
DIV
SPAN
SPAN
SPAN
...
DOM: Document Object Model
2008 - 2009©ISEL/DEETC/STI – Programação na Internet
Interfaces de registo de Eventos
32
EventTarget interface CharacterData : Node {void addEventListener(in DOMString type, in EventListener listener,
in boolean useCapture); void removeEventListener(in DOMString type, in EventListener listener,
in boolean useCapture); boolean dispatchEvent(in Event evt) raises(EventException);};
EventListenerinterface EventListener { void handleEvent(in Event evt); };
DOM: Document Object Model
2008 - 2009©ISEL/DEETC/STI – Programação na Internet
Registo de Handlers• O registo de handlers é efectuado sobre o objecto “gerador” de eventos:
– node.["on" + type] = f;
– node.addEventListener(type, f, false);
Atenção!– Nos browsers que não implementam o especificação DOM nível 2 para eventos
(e.g. Microsoft IE), a forma de registo anterior não funciona
33
window.onload = function () { alert(“página carregada!”);}
Da forma clássica
window.addEventListener(“load”, function () { alert(“página carregada!”);}, false);
W3C DOM
DOM: Document Object Model
2008 - 2009©ISEL/DEETC/STI – Programação na Internet
Captura de Eventos• No registo dos handlers, é possível especificar se é pretendido capturar o
evento antes de ele ser processado pelo nó destinatário
34
div.addEventListener(“click”, function () { alert(“página carregada!”);}, true);
DIV
SPAN
SPAN
SPAN
... • Qualquer evento que seja gerado no nó <div> ou em algum dos seus descendentes, é, em primeiro lugar, notificado o nó <div>
• Só depois serão notificados os nós descendentes (que tiverem capturado o evento) e finalmente o nó destinatário
• É possível cancelar a captura evocando o método preventDefault (ou retornando false, no IE!)
1
2
DOM: Document Object Model
2008 - 2009©ISEL/DEETC/STI – Programação na Internet
Bubbling• Uma vez processado o evento pelo nó destinatário, são evocados os
handlers dos nós ascendentes, pela ordem inversa da fase anterior (captura)
35
div.addEventListener(“click”, function () { alert(“página carregada!”);}, false);
DIV
SPAN
SPAN
SPAN
... • É possível evitar que o evento seja propagado para os ascendentes – evocando o método stopPropagation
• Note-se que nem todos os eventos suportam bubbling (e.g load) e nem todos podem ser cancelados (e.g. mousemove )
3
2
DOM: Document Object Model
2008 - 2009©ISEL/DEETC/STI – Programação na Internet
Interface Evento
36
Eventinterface // PhaseType const unsigned short CAPTURING_PHASE = 1; const unsigned short AT_TARGET = 2; const unsigned short BUBBLING_PHASE = 3;
readonly attribute DOMString type; readonly attribute EventTarget target; readonly attribute EventTarget currentTarget; readonly attribute unsigned short eventPhase; readonly attribute boolean bubbles; readonly attribute boolean cancelable; readonly attribute DOMTimeStamp timeStamp; void stopPropagation(); void preventDefault(); void initEvent(in DOMString eventTypeArg, in boolean canBubbleArg, in boolean cancelableArg);};
DOM: Document Object Model
2008 - 2009©ISEL/DEETC/STI – Programação na Internet
Handlers e eventos• De acordo com a especificação DOM, é sempre passado como parâmetro
ao handler o evento
Atenção!!! • Nos browsers da Microsoft não é passado nenhum evento como
parâmetro – tem de ser consultado o objecto global window.event
37DOM: Document Object Model
2008 - 2009©ISEL/DEETC/STI – Programação na Internet
Eventos DOM • Na especificação DOM nível 2, estão definidos 3 tipos de eventos:
– Eventos da User Interface• e.g. DomFocusIn
– Eventos de rato• e.g. click
– Eventos de alteração da estrutura do documento (Mutation Events)• e.g. DOMNodeInserted
• A especificação DOM nível três define também eventos de teclado
38
Event
UIEvent
MouseEventMutationEvent
DOM: Document Object Model
2008 - 2009©ISEL/DEETC/STI – Programação na Internet
Eventos de Rato• Os eventos de rato são aqueles que são mais utilizados:
– click, mousedown, mouseup, mouseover, mouseout, mousemove
• Quando são deste tipo, os eventos contêm também as propriedades:
39
Propriedade DescriçãoaltKey, ctrlKey, metaKey, shiftKey
true, quando a tecla estava premida no momento da ocorrência do evento
button Um inteiro que indica qual dos botões do rato foi premido: 1 = left, 2 = middle, 3 = right.
relatedTarget MouseEnter e MouseLeave
screenX, screenY A coordenada do ponteiro do rato relativa ao ecrã
clientX, clientY A coordenada do ponteiro do rato relativa à área de cliente (e.g browser)
DOM: Document Object Model
2008 - 2009©ISEL/DEETC/STI – Programação na Internet
Bibliografia
40
W3C Document Object Model http://www.w3.org/DOM/
Dom Technical Reports http://www.w3.org/DOM/DOMTR
40