JavaScript Developer

segunda-feira, outubro 23, 2006

DOM - Básico

E ae galera! Pow, to atrasadão com vocês... mal ae, tava sem tempo no trabalho esses dias, mas hoje vamos voltar aos estudos :)

O que raios é DOM?
DOM é a sigla para Document Object Model (Modelo de Objecto de Documento), ele é uma API para ler e escrever XML (é a padrão da W3C e tem sua implementação na maioria das linguagens atuais). Com o DOM é possivel localizar elementos dentro de um XML, alterar atributos, criar novos elementos e outros recursos.

DOM em JavaScript
No JavaScript particularmente, o DOM é de vital importância, enquanto em outras linguages você usa o DOM para realmente ler, escrever e salvar documentos XML, no JavaScript ele é usado para mudar a página dinâmicamente. Você deve saber que a página web é mostrada na tela após o conteudo HTML (ou XHTML) ser carregado, a grande jogava do DOM no JavaScript é que com ele você muda os atributos do HTML atual, e automaticamente a exibição é atualizada! Se você associar isso ao fato de conseguir alterar também o CSS dos elementos, os efeitos que podem ser gerados estão além do que muita gente pensa quanto a capacidade de sites. Essa arte de mexer com elementos usando DOM no JavaScript é chamada DHTML, quando você ver esse nome na net, não se assuste, DHTML não é uma linguagem, é apenas o uso do JavaScript para mexer com HTML ;)

Começando com DOM
Bom, vamos passar a escrever agora todo o HTML no código, pois como vamos mexer no HTML, não da pra ter apenas código JavaScript (eu me refiro ao usar o esqueleto de código que eu passei no primeiro artigo, e realmente, é possivel fazer DHTML sem ter código HTML prévio, mas vamos deixar isso para depois).

Nosso documento HTML que será usado inicialmente (use ele, o resto iremos colocar somente na tag script):

<html>
<head>
<title> :: JavaScript Developer - Aprendendo DOM :: </title>
<script type="text/javascript">
//o codigo vira aqui
</script>
</head>
<body>
<form id="meuFormulario">
<table>
<tr>
<td valign="top">Linguagens que programa:</td>
<td>
<div id="camposCheck">
<input type="checkbox" name="linguagens[]" /> PHP<br />
<input type="checkbox" name="linguagens[]" /> JavaScript<br />
<input type="checkbox" name="linguagens[]" /> C++<br />
<input type="checkbox" name="linguagens[]" /> Java<br />
<input type="checkbox" name="linguagens[]" /> CSS<br />
</div>
<div id="fastCheckDiv" style="display: none;">
<a href="#" id="marcaTodosLink">Marcar Todos</a>
<a href="#" id="desmarcaTodosLink">Desmarcar Todos</a>
</div>
</td>
</tr>
<tr>
<td></td>
<td><button type="submit">Enviar Formulário</button></td>
</tr>
</table>
</form>
</body>
</html>


Iremos comecar com o mais simples, os formulários, mas antes eu gostaria de expor um conceito muito bem aceito hoje em dia, que é o conceito do JavaScript "não obstrutivo".

JavaScript não obstrutivo
O que seria isso? É simplesmente fazer o uso do JavaScript sem faze-lo obrigatório para visualização, fazendo com que dessa forma, o JavaScript seja apenas um adicional, e não fundamental. E como fazer isso? A primeira coisa a ser feita, é deixar tudo funcionando sem JavaScript, como vocês podem ver, o formulário do código acima não tem nada de JavaScript, mas se clicar-mos no botão de enviar, o formulário vai ser enviado sem nenhum problema, entao ja temos a solução no HTML, e agora iremos apenas incrementar mais interatividade. No JavaScript não obstrutivo nós não colocamos código JavaScript no meio do HTML, no lugar de fazer isso apenas nomeamos elementos com ID, e depois os pegamos usando o DOM!

Voltando ao formulario
OK, nesse formulário iremos incrementar uma função pra marcar e desmarcar todos os checkbox mais facilmente. obs: eu ia fazer uma validação com um campo de nome também, mas isso usuária muito código, e parar um evento de forma não obstrutiva não é tão simples, entao prefiro deixar isso para quando formos falar de eventos em futuros artigos.

Como sempre, primeiro o código, depois explicações ;)

function $(obj) {
return document.getElementById(obj);
}

function marcaBoxes(marcar) {
var boxesContainer = $('camposCheckDiv');
var childs = boxesContainer.childNodes;

for(var i = 0; i < childs.length; i++) {
var node = childs[i];

if(node.nodeType == 1 && node.tagName == "INPUT")
node.checked = marcar;
}
}

window.onload = function() {
var marcaTudoObj = $('marcaTodosLink');
var desmarcaTudoObj = $('desmarcaTodosLink');
var fastCheckObj = $('fastCheckDiv');

marcaTudoObj.onclick = function() {
marcaBoxes(true);
};

desmarcaTudoObj.onclick = function() {
marcaBoxes(false);
};

fastCheckObj.style.display = '';
};


Vamos com calma, esse script tem várias coisas novas, vamos pelo começo:

A função $(obj) -> eu já disse antes que para mexer com os elementos de forma não obstrutiva, devemos colocar ID neles, para pegar isso com o DOM, mas eu ainda não tinha falado como fazer isso. Primeiro de tudo, a variável pré-definida document é o objeto principal do DOM, vamos falar mais sobre ela depois, por enquanto, saibamos que ela tem um método chamado getElementById(), e como claramente o nome diz, esse método serve justamente para pegar a referência para em elemento dentro do HTML atual. O que a função $() faz é apenas servir de atalho para document.getElementById(), porque convenhamos, escrever document.getElementById() o tempo todo é uma me***. Futuramente vamos ver como deixar essa função ainda melhor.

A função marcaBoxes(marcar) -> essa é a função principal para o nosso sistema, é ela que vai lá e marca / desmarca os checkbox, o parêmetro marcar serve para indicar se ela vai marcar ou desmarcar os checkbox. Vamos estuda-la passo a passo:

var boxesContainer = $('camposCheckDiv'); => essa linha pega o elemento DIV que está contendo os nossos checkbox, precisamos de algo que circunde nosso checkbox para poder pega-los de forma dinâmica e eficiente

var childs = boxesContainer.childNodes; => essa é legal, todos os objetos HTML tem uma propriedade chamada childNodes, o childNodes é um array contendo todos as referencias para os elementos dentro do dele. Ou seja, como nossos checkboxes estão dentro de boxesContainer, então entre os childNodes do boxesContainer estão todos os nossos checkboxes que devem ser marcados / desmarcados

for(var i = 0; i < childs.length; i++) { => iniciamos nosso loop pelos childNodes

var node = childs[i]; => colocamos um nó atual numa variável, apenas para ficar mais claro

if(node.nodeType == 1 && node.tagName == "INPUT") => essa linha aqui é importante, primeiro verificamos se o nó é um elemento realmente, os elementos HTML (aqueles entre tags) são representados pelo valor 1, mas existem outros também:

1 - elemento HTML, exemplo: <p>...</p>
2 - atributo, exemplo: align="center"
3 - texto, exemplo: conteudo de alguma coisa
8 - comentário, exemplo: <!-- comentario html -->
9 - document, é o nó principal do XML, exemplo: <html>
10 - definição do documento, exemplo: <!DOCTYPE HTML PUBLIC "-//W3C //DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

pela lista podemos ver que o único em que estamos interessados é o número 1. O segundo item verifica se o nosso elemento é um input (lembre-se, também temos uns <br /> no meio), um detalhe, a propriedade tagName sempre fica em maiúsculo, independende de como vocês a escreveu no HTML.

node.checked = marcar; -> finalmente, após tudo estamos marcado ou desmarcando o checkbox (de acordo com o parâmetro passado), a propriedade checked pertence apenas a radios e checkboxes, ela indica se ele esta ou não marcado, e pode ser usada para definir também (como nós fizemos).

Ufa, terminamos a função principal, vamos a parte do código que faz a nossa mágica da não obstrução:

window.onload = function() {

Colamos o codigo dentro dessa função por um motivo simples, nós vamos mexer com o HTML do site, se tentarmos fazer isso antes do documento ser carregado vai dar erro (pois os elementos ainda não vão existir). Por hora, apenas saiba que window.onload é o evento que dispara quando a página é carregada.

var marcaTudoObj = $('marcaTodosLink');
var desmarcaTudoObj = $('desmarcaTodosLink');
var fastCheckObj = $('fastCheckDiv');


Nessas linhas pegamos as referências para os elementos HTML.

marcaTudoObj.onclick = function() {
marcaBoxes(true);
};

desmarcaTudoObj.onclick = function() {
marcaBoxes(false);
};


Agora colocamos os eventos, estamos dizendo que quando clicar, é para executar a função (que vai logo em seguida). Essa com certeza não é a melhor maneira para colocar eventos nos objetos, mas é a mais simples.

fastCheckObj.style.display = '';

E finalmente, nós fazemos os links ficarem visíveis alterando o css dele (vejam como é simples alterar um css, apenas digita-se .style, depois .propriedade e altera). O motivo de ter deixado os links invisíveis, pensem bem, esses links só funcionam se o JavaScript estiver ativado, então, se o JavaScript estiver desativado eles irão permanecer invisíveis, dessa forma o clinte não vai tentar clicar numa coisa que não faz nada.

Mais explicações
Talvez você tenha entendido, talvez não, mas o DOM usa uma estrutura de árvore para guardar os elementos, se você já estudou e sabe oque é isso, ótimo, se não, pense no windows explorer, quando vemos as pastas à esquerda, aquilo é uma estrutura de árvore, cada "nó" pai pode ter varios "nós" filhos, e assim sucessivamente, do mesmo jeito que uma árvore tem galhos, e galhos sobre galhos... No XML temos o nó principal (no HTML seria a propria tag <html>), e esse nó tem varios filhos (<head> <body>), que pode sua vez tem mais varios... Usando esse pensamentos podemos percorrer o documento do jeito que quizermos. Vou colocar os principais atributos usados:

objeto.childNodes - coleção com os nós filhos
objeto.parentNode - nó pai (o nó em qual ele está agrupado)
objeto.nextSibling - o próximo nó (ainda dentro do mesmo pai)
objeto.previousSibling - nó anterior (dentro do mesmo pai)
objeto.tagName - nome da tag
objeto.nodeName - nome da tag (mesma coisa que o anterior)


Com isso você pode "navegar" a vontade pelo documento a partir de qualquer lugar. Existe uma coisa do DOM chamada XPath, com ele você facilmente localiza nodes no documento, eu sinceramente ainda não estudei o XPath no JavaScript, mas sei que ele existe, qualquer dia desses eu posto só sobre isso ;)

Por hoje ficamos por aqui, no próximo artigo vou falar sobre DHTML, vamos fazer alguns efeitos no site. Como sempre, aquela referência esperta (essa é meio grande XD) dos objetos html em geral:

Generic HTML Element Object (Document Object)
Generic (X)HTML elements have the form described here. This list of properties, methods, and event handlers are common to almost all (X)HTML element objects and are, in fact, the only properties, methods, and event handlers defined for a large number of very basic elements, such as <b>, <i>, and <u>. Each of these objects corresponds to an occurrence of an (X)HTML element on the page. Access to one of these objects is achieved through standard DOM methods like document.getElementById().

Note Some properties do not have a well-defined meaning for particular objects, even though the properties may be defined for them. For example, blurring an <hr> tag is interesting given that it is difficult to focus the object in general Web use.


Properties
accessKey Single character string indicating the hotkey that gives the element focus. (IE4+)

all[] Collection of elements enclosed by the object. (IE4+)

align String specifying the alignment of the element, for example, "left". This property is defined only for display elements such as b, big, cite, and so on. (IE4+)

attributes[] Collection of read-only attributes for the element. (IE5+, MOZ/N6+, DOM1)

begin Sets or retrieves delay before timeline begins playing the element. See MSDN. (IE5.5+, SMIL)

behaviorUrns[] Collection of DHTML Behaviors attached to the node. (IE5+)

canHaveChildren Read-only Boolean value indicating whether the element can have child nodes. (IE5+)

canHaveHTML Read-only Boolean indicating whether the element can enclose HTML markup. (IE5.5+)

childNodes[] Read-only collection of child nodes of the object. (IE5+, MOZ/N6+, DOM1)

children[] Read-only collection of child nodes. This is IE’s pre-DOM equivalent of childNodes[]. (IE4+)

className String holding value of the CSS class(es) the element belongs to. (IE4+, MOZ/N6+, DOM1)

clientHeight Read-only numeric value indicating the height of the element’s content area in pixels. (IE4+)

clientLeft Read-only numeric value indicating the difference between the offsetLeft property and the beginning of the element’s content area, in pixels. (IE4+)

clientTop Read-only numeric value indicating the difference between the offsetTop property and the beginning of the element’s content area, in pixels. (IE4+)

clientWidth Read-only numeric value indicating the width of the element’s content area in pixels. (IE4+)

contentEditable String determining whether the element’s content is editable. Values are "inherit", "true", or "false". A value of "inherit" means that it will inherit the contentEditable property of its parent (this value is the default). This property is useful for making table data cells editable. Elements with disabled set to true are not editable, no matter what value this property has. Corresponds to the contenteditable attribute. (IE5.5+)

currentStyle Read-only reference to the Style object reflecting all styles applied to the element, including global (default) style. (IE5+)

dir String holding the text direction of text enclosed by the element. If set, its value is either "ltr" (left to right) or "rtl" (right to left). (IE5+, MOZ/N6+, DOM1)

disabled Boolean indicating whether the element is disabled (grayed out). (IE4+)

document An undocumented reference to the Document in which the element is contained. (IE4+)

filters[] Collection of Microsoft CSS Filters applied to the element. (IE4+)

firstChild Read-only reference to the first child node of the element, if one exists (null otherwise). (IE5+, MOZ/N6+, DOM1)

hasMedia Read-only Boolean indicating whether the element is an HTML+TIME media element. (IE5.5+)

hideFocus Boolean indicating whether the object gives a visible cue when it receives focus. (IE5.5+)

id String holding the unique alphanumeric identifier for the element. Commonly assigned using the id HTML attribute and used as the target for getElementById(). This unique identifier is not only important for scripting, but also for binding of CSS. (IE4+, MOZ/N6+, DOM1)

innerHTML String holding the HTML content enclosed within the element’s tags. (IE4+, MOZ/N6+)

innerText String holding the text enclosed by the element’s tags. This text is not interpreted as HTML, so setting it to a value like "<b>Important</b>" will result in "<b>Important</b>" being displayed, rather than "Important" with boldfaced font. (IE4+)

isContentEditable Read-only Boolean indicating if the user can edit the element’s contents. (IE5.5+)

isDisabled Read-only Boolean indicating if the user can interact with the object. (IE5.5+)

isTextEdit Read-only Boolean indicating if a TextRange object can be created using the object. (IE4+)

lang String holding language code for the content the element encloses. Corresponds to the lang HTML attribute. For a full list of valid values, see RFC 1766 (http://www.ietf.org/rfc/rfc1766.txt?number=1766), which describes language codes and their formats. (IE4+, MOZ/N6+, DOM1)

language String indicating the scripting language in use. (IE4+)

lastChild Read-only reference to the last child node of the element, if one exists (null otherwise). (IE5+, MOZ/N6+, DOM1)

localName Read-only string indicating the "local" XML name for the object. (MOZ/N6+)

namespaceURI Read-only string indicating the XML Namespace URI for the object. (MOZ/N6+)

nextSibling Read-only reference to next sibling of the node, for example, if its parent has multiple children. (IE5+, MOZ/N6+, DOM1)

nodeName Read-only string containing name of the node, the name of the tag to which the object corresponds, for example, "H1". (IE5+, MOZ/N6+, DOM1)

nodeType Read-only number holding the DOM defined node type. For example, element nodes have node type 1. A list of the common node types can be found in the following table. (IE5+, MOZ/N6+, DOM1) [tabela 1]

nodeValue String containing value within the node (or null if no value). (IE5+, MOZ/N6+, DOM1)

offsetHeight Read-only numeric value indicating the height of the element in pixels. (IE4+, MOZ/N6+)

offsetLeft Read-only numeric value indicating the pixel offset of the left edge of the element, relative to its offsetParent. (IE4+, MOZ/N6+)

offsetParent Read-only reference to the object relative to which the offsetHeight/Width/Left/Top is calculated. (IE4+, MOZ/N6+)

offsetTop Read-only numeric value indicating the pixel offset of the top edge of the element, relative to its offsetParent. (IE4+, MOZ/N6+)

offsetWidth Read-only numeric value indicating the width of the element in pixels. (IE4+, MOZ/N6+)

outerHTML String holding the HTML content enclosed within (and including) the element’s tags. (IE4+)

outerText String holding the text enclosed by (and including) the element’s tags. (IE4+)

ownerDocument Read-only reference to the Document in which the element is contained. (IE5+, MOZ/N6+, DOM1)

parentElement Reference to the node’s parent. This is IE’s pre-DOM equivalent of parentNode. (IE4+)

parentNode Read-only reference to the parent of the object (or null if none exists). (IE4+, MOZ/N6+, DOM1)

parentTextEditv Read-only reference to the innermost container element outside of the current object that is capable of creating a TextRange containing the current element. (IE4+)

prefixv Read-only string containing the "prefix" XML name for the object. (MOZ/N6+)

previousSibling Read-only reference to previous sibling of the node, for example, if its parent node has multiple children. (IE5+, MOZ/N6+, DOM1)

readyState Read-only string containing the current state of the object. Values include "uninitialized", "loading", "loaded", "interactive" (not finished loading but able to respond to user actions), and "complete". Objects progress through each of these states until they have completed loading, though some objects may skip some intermediate steps (for example, pass from "uninitialized" directly to "complete"). This property is very useful in determining whether an element has completed loading. However, you should always make sure the object exists in the Document before attempting to read this property (otherwise, a runtime error will be thrown because you would be attempting to read a property of an object not yet defined). Note that an <object>s readyState is given by the integers 0 through 4 (with the same meaning). (IE4+)

recordNumber Read-only numeric value indicating the record number of the data set from which the element was generated. (IE4+)

runtimeStyle Reference to the Style object that reflects the current (runtime) style characteristics of the element. (IE5+)

scopeName Read-only string containing the XML scope for the object. (IE5+)

scrollHeight Numeric read-only value indicating the total height in pixels of the element’s content area, no matter how much is displayed on screen. (IE4+)

scrollLeft Numeric value indicating the distance in pixels from the left edge of the object to the leftmost edge of the object that is currently displayed. (IE4+)

scrollTop Numeric value indicating the distance in pixels from the top edge of the object to the topmost edge that is currently displayed. (IE4+)

scrollWidth Numeric read-only value indicating the total width in pixels of the object’s content area, no matter how much is displayed on screen. (IE4+)

sourceIndex Read-only number indicating the index of the element in the document.all[] collection. (IE4+)

style Reference to the inline Style object for the element. (IE4+, N4+, DOM2)

syncMaster Specifies whether time container must synchronize with the element. See MSDN. (IE5.5+, SMIL)

tabIndex Numeric value indicating the tab order for the object. Elements with positive values for this property are tabbed to in order of increasing tabIndex (before any others). Elements with zero for this property (the default) are tabbed to in the order they occur in the document source. Elements with negative values are not tabbed to at all. (IE4+)

tagName String containing the name of the tag to which the object corresponds, for example, "H1." (IE5.5+, MOZ/N6+, DOM1)

tagUrn String containing the URN of the XML Namespace for the object. (IE5+)

timeContainer Sets or retrieves the type of timeline associated with the element. (IE5.5+, SMIL)

title String containing advisory text for the element. (IE4+, MOZ/N6+, DOM1)

uniqueID An auto-generated read-only unique id for this element. (IE5+)

Methods
addBehavior(url) Attaches the DHTML Behavior referenced by string url to the element. (IE5+)

addEventListener(whichEvent, handler, direction) Instructs the object to execute the function handler whenever an event of type given in the string whichEvent (for example, "click") occurs. The direction is a Boolean specifying the phase in which to fire, true for capture or false for bubbling. (MOZ/N6+, DOM2)

appendChild(newChild) Appends newChild to end of the node’s childNodes[] list. (IE5+, MOZ/N6+, DOM1 Core)

applyElement(newElement [, where]) "Applies" one element to another by enclosing one within the other. If where is omitted or has value "outside", the object referenced by newElement becomes the parent of the current element. Otherwise, newElement becomes the only child of the current element, enclosing all of the current element’s children. (IE5+)

attachEvent(whichHandler, theFunction) Attaches the function theFunction as a handler specified by the string whichHandler, for example, "onclick". (IE5+)

blur() Removes focus from the element. (IE5+ for most elements. For form fields N2+ or N3+ and IE3+ or IE4+ and DOM1, listed specifically for each object)

clearAttributes() Clears all nonessential HTML attributes from the element (leaves id, dir, etc.). (IE5+)

click() Simulates a mouse click at the object. (IE4+)

cloneNode(cloneChildren) Clones the node and returns the new clone. If cloneChildren is true, the returned node includes the recursively constructed subtree of clones of the node’s children. (IE5+, MOZ/N6+, DOM1 Core)

componentFromPoint(x, y) Returns a string that gives information about the pixel coordinate (x,y) in the client window with respect to the current element. The string returned may have one of the values in the following table [tabela 2]. The return value specifies whether the coordinate is inside of the element (""), outside of the element ("outside"), or a part of the various scrolling mechanisms that may be displayed for the element.

This method is often used with events to determine where user activity is taking place with respect to a particular element and to take special actions based on scroll bar manipulation. (IE5+)

contains(element) Returns a Boolean indicating if the object given in element is contained within the element. (IE4+)

detachEvent(whichHandler, theFunction) Instructs the object to cease executing the function theFunction as a handler given the string whichHandler, for example, "onclick". (IE5+)

dispatchEvent(event) Causes the Event instance event to be processed by the object’s appropriate handler. Used to redirect events. (MOZ/N6+, DOM2)

dragDrop() Initiates a drag event at the element. (IE5.5+)

fireEvent(handler [, event]) Causes the event handler given by the string handler to fire. If an Event instance was passed as event, the new event created reflects the properties of event. (IE5.5+)

focus() Gives focus to the element.

getAdjacentText(where) Returns the string of text corresponding to the text string at position where, with respect to the current node. The where parameter is a string with the following values [tabela 3]

There is no standard DOM method that mimics this behavior. Instead, you must examine the previousSibling, firstChild, lastChild, or nextSibling (in order corresponding to the values of where in the preceding table) and extract the string manually from their text node(s). (IE5+)

getAttribute(name) Returns a string containing the value of the attribute specified in the string name or null if it does not exist. (IE4+, MOZ/N6+, DOM1 Core)

getAttributeNode(name) Returns the attribute node corresponding to the attribute in the string name. (IE6+, MOZ/N6+, DOM1 Core)

getBoundingClientRect() Retrieves a TextRectangle with properties top, bottom, left, right indicating the pixel values of the rectangle in which the element’s content is enclosed. (IE5+)

getClientRects() Retrieves a collection of TextRectangle objects, which give the pixel coordinates of all bounding rectangles contained in the element. (IE5+)

getElementsByTagName(tagname) Retrieves a collection of elements corresponding to the tag given in string tagname. A value of "*" retrieves all tags. (IE5+, MOZ/N6+, DOM1 Core)

getExpression(propertyName) Retrieves the string giving the dynamic property expression for the property/attribute named propertyName. (IE5+)

hasAttribute(name) Returns a Boolean indicating if the attribute given in string name is defined for the node (explicitly or by default). (MOZ/N6+, DOM2 Core)

hasAttributes() Returns a Boolean indicating if any attributes are defined for the node. (MOZ/N6+, DOM2 Core)

hasChildNodes() Returns a Boolean indicating if the node has children. (IE5+, MOZ/N6+, DOM1 Core)

insertAdjacentElement(where, element) Inserts the element object given in element adjacent to the current element in the position given by the string where (IE5+).The possible values for where include these [tabela 4]

insertAdjacentHTML(where, text) Inserts the HTML given in string text adjacent to the current element according to the string where. See table under insertAdjacentElement() for the meaning of this parameter. The text is parsed and added to the document tree. (IE5+)

insertAdjacentText(where, text) Inserts the text given in string text adjacent to the current element according to the string where. See table under insertAdjacentElement() for the meaning of this parameter. The text is not parsed as HTML. (IE5+)

insertBefore(newChild, refChild) Inserts node newChild in front of refChild in the childNodes[] list of refChild's parent node. (IE5+, MOZ/N6+, DOM1 Core)

isSupported(feature [, version]) Returns a Boolean indicating whether feature and version given in the argument strings are supported. (MOZ/N6+, DOM2 Core)

mergeAttributes(source [, preserve]) Merges all attributes, styles, and event handlers from the element node source into the current element. (IE5+)

normalize() Recursively merges adjacent text nodes in the sub-tree rooted at this element. (IE6+, MOZ/N6+, DOM1 Core)

releaseCapture() Disables universal mouse event capturing at that object. (IE5+)

removeAttribute(name) Removes attribute corresponding to string name from the node. (IE4+, MOZ/N6+, DOM1 Core)

removeAttributeNode(attribute) Removes the attribute node given by node attribute and returns the removed node. (IE6+, MOZ/N6+, DOM1 Core)

removeBehavior(id) Removes the DHTML Behavior associated with id (previously returned by attachBehavior()) from the element. (IE4+)

removeChild(oldChild) Removes oldChild from the node’s children and returns a reference to the removed node. (IE5+, MOZ/N6+, DOM1 Core)

removeEventListener(whichEvent, handler, direction) Removes function handler as a handler for the event given in the string whichEvent (for example, "click") for the phase given by the Boolean direction. (MOZ/N6+, DOM2)

removeExpression(propertyName) Removes dynamic property expression for the property given in the string propertyName. (IE5+)

replaceAdjacentText(where, text) Replaces the text at position where relative to the current node with the text (non-HTML) string text (IE5+). Possible values for where include [tabela 5]

replaceChild(newChild, oldChild) Replaces the node’s child node oldChild with node newChild. (IE5+, MOZ/N6+, DOM1 Core)

replaceNode(newNode) Replaces the current node with newNode. (IE5+)

scrollIntoView([alignToTop]) Causes the object to be immediately scrolled into the viewable area of the window. If alignToTop is true or omitted, the top of the object is aligned with the top of the window (if possible). Otherwise, if alignToTop is false, the object is scrolled so that the bottom of the object is aligned with the bottom of the viewable window. (IE4+)

setActive() Sets the object as the active object without giving it focus. (IE5.5+)

setAttribute(name, value) Sets a new attribute for the node with name and value given by the string arguments. (IE4+, MOZ/N6+, DOM1 Core)

setAttributeNode(newAttr) Adds the attribute node newAttr (replacing and returning any attribute node with the same name). (IE6+, MOZ/N6+, DOM1 Core)

setCapture([containerCapture]) Causes all mouse events occurring in the document to be sent to this object. (IE5+)

setExpression(property, expression [, language]) Sets the expression given in string expression as the dynamic expression for the property given in string property. The optional language parameter specifies which scripting language the expression is written in, for example, "VBscript" (JScript is the default). Commonly used as a method of element nodes and Style objects. Used for setting dynamic expressions. (IE5+)

swapNode(node) Exchanges the location of the object with node in the object hierarchy. (IE5+)

unwatch(property) Removes the watchpoint on the property given in the string property. (N4+)

watch(property, handler) "Watches" the property given in string property and invokes the function handler whenever its value changes. The handler is passed the name of the property, the old value, and the value to which it is being set. Any value the function returns is interpreted as the new value for the property. (N4+)

Notes
With the exception of the object scriptable under traditional models (Form, Image, and so on), most elements become scriptable in Internet Explorer 4+, Mozilla/Netscape 6+, and DOM1.

HTML elements are referred to both in uppercase and lowercase under the DOM, so <p> and <P> are both equivalent to an HTMLParagraph object.


Tabela 1











































Node Type Number Type Description Example
1 Element An HTML or XML element <p>…</p>
2 Attribute An attribute for an HTML or XML element align="center"
3 Text A fragment of text that would be enclosed by an HTML or XML element This is a text fragment!
8 Comment An HTML comment <!-- This is a comment -->
9 Document The root document object, namely the top element in the parse tree <html>
10 DocumentType A document type definition <!DOCTYPE HTML PUBLIC "-//W3C

//DTD HTML 4.01 Transitional//EN"

"http://www.w3.org/TR/html4/loose.dtd">


Tabela 2

























































































Return Value Component at the Given Coordinate
"" Component is inside the client area of the object.
"outside" Component is outside the bounds of the object.
"scrollbarDown" Down scroll arrow is at the specified location.
"scrollbarHThumb" Horizontal scroll thumb or box is at the specified location.
"scrollbarLeft" Left scroll arrow is at the specified location.
"scrollbarPageDown" Page-down scroll bar shaft is at the specified location.
"scrollbarPageLeft" Page-left scroll bar shaft is at the specified location.
"scrollbarPageRight" Page-right scroll bar shaft is at the specified location.
"scrollbarPageUp" Page-up scroll bar shaft is at the specified location.
"scrollbarRight" Right scroll arrow is at the specified location.
"scrollbarUp" Up scroll arrow is at the specified location.
"scrollbarVThumb" Vertical scroll thumb or box is at the specified location.
"handleBottom" Bottom sizing handle is at the specified location.
"handleBottomLeft" Lower-left sizing handle is at the specified location.
"handleBottomRight" Lower-right sizing handle is at the specified location.
"handleLeft" Left sizing handle is at the specified location.
"handleRight" Right sizing handle is at the specified location.
"handleTop" Top sizing handle is at the specified location.
"handleTopLeft" Upper-left sizing handle is at the specified location.
"handleTopRight" Upper-right sizing handle is at the specified location.


Tabela 3





















Value of where String Returned
"beforeBegin" Text immediately preceding element’s opening tag (back to but not including first element encountered).
"afterBegin" Text immediately following the element’s opening tag (up to but not including the first nested element).
"beforeEnd" Text immediately preceding the element’s closing tag (back to but not including the closing tag of the last enclosed element).
"afterEnd" Text immediately following element’s closing tag (up to but not including the first following tag).


Tabela 4





















Value of where Effect
"beforeBegin" Inserts immediately before the object.
"afterBegin" Inserts after the start of the object but before all other content.
"beforeEnd" Inserts immediately before the end of the object, after all other content.
"afterEnd" Inserts immediately after the end of the object.


Tabela 5





















Value of where Effect
"beforeBegin" Replaces text immediately before the object (back to but not including first tag or end tag encountered).
"afterBegin" Replaces text at the start of the object but before all other enclosed content (up to but not including first opening tag).
"beforeEnd" Replaces text immediately before the end of the object, after all other content (back to but not including last tag or closing tag).
"afterEnd" Replaces text immediately after the element’s closing tag (up to but not including the next tag).

6 Comments:

  • ae wilker... bom cara vlw por postar aqui... vc ta dedicante um tempo seu pra ajudar quem tem interesse na área... bem.. sou daqui de recife também tou pagando cadeira de javascript =] e seus posts ajudam bastante ;D

    vlw ae

    By Anonymous Anônimo, at 10:52 PM  

  • obrigado por dedicar tanto tempo para fazer um material muito bom como esse!
    abraço!

    By Anonymous Anônimo, at 4:43 PM  

  • Mto bom kra!

    Pra gente que tá começando, e fica mais no ctrl+c ctrl+v, é ótimo qdo a gente entende o que tá realmente acontecendo xD, eu mesmo já usei bastante coisa que só entendi com suas dicas aqui ! Seu blog virou leitura de rotina ! vlw!

    By Anonymous Anônimo, at 12:00 PM  

  • Muito bom o post (só um pouco grande demais hehe).

    Mas curti pra caramba.

    Um bom local pra você indicar a leitura relativa a DOM (e diversos outros assuntos) é o MDC (Mozilla Developer Center).
    Você também poderia ajudar bastante por lá. :)

    By Blogger Micox - Náiron J. C. G., at 5:58 PM  

  • mtu bom msm hein wilker...

    tá de parabens... tem muitas coisas aqui que meus professores da faculdade nem comentaram... a leitura é fácil e limpa, o blog tá muito bem organizado, você tá de parabéns de verdade.

    Estou visitando o blog direto agora, não pare com o seu exelente trabalho. Continue com as colunas.

    By Anonymous Anônimo, at 1:14 AM  

  • Que saudades desse blog, pensei que tinha morrido (o blog) =~~

    DOM <3

    By Blogger Unknown, at 5:17 PM  

Postar um comentário

<< Home