From 074785cea106179cb3305637055ab0a009ca74f2 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:42:52 -0500 Subject: initial commit --- .../web/api/document/activeelement/index.html | 164 +++++++++ files/pt-br/web/api/document/alinkcolor/index.html | 36 ++ files/pt-br/web/api/document/anchors/index.html | 107 ++++++ files/pt-br/web/api/document/bgcolor/index.html | 35 ++ files/pt-br/web/api/document/body/index.html | 44 +++ .../pt-br/web/api/document/characterset/index.html | 65 ++++ files/pt-br/web/api/document/close/index.html | 27 ++ files/pt-br/web/api/document/compatmode/index.html | 42 +++ .../pt-br/web/api/document/contenttype/index.html | 46 +++ .../web/api/document/createelement/index.html | 82 +++++ .../web/api/document/createelementns/index.html | 90 +++++ .../web/api/document/currentscript/index.html | 99 +++++ .../pt-br/web/api/document/defaultview/index.html | 28 ++ files/pt-br/web/api/document/designmode/index.html | 104 ++++++ files/pt-br/web/api/document/doctype/index.html | 59 +++ files/pt-br/web/api/document/document/index.html | 87 +++++ .../web/api/document/documentelement/index.html | 43 +++ .../pt-br/web/api/document/documenturi/index.html | 53 +++ .../web/api/document/elementfrompoint/index.html | 132 +++++++ .../web/api/document/elementoregistrado/index.html | 132 +++++++ .../pt-br/web/api/document/execcommand/index.html | 174 +++++++++ files/pt-br/web/api/document/fullscreen/index.html | 83 +++++ .../web/api/document/getelementbyid/index.html | 133 +++++++ .../api/document/getelementsbyclassname/index.html | 104 ++++++ .../web/api/document/getelementsbyname/index.html | 90 +++++ .../api/document/getelementsbytagname/index.html | 113 ++++++ .../pt-br/web/api/document/getselection/index.html | 8 + files/pt-br/web/api/document/hasfocus/index.html | 146 ++++++++ files/pt-br/web/api/document/head/index.html | 102 ++++++ files/pt-br/web/api/document/height/index.html | 44 +++ files/pt-br/web/api/document/images/index.html | 38 ++ .../web/api/document/implementation/index.html | 52 +++ files/pt-br/web/api/document/importnode/index.html | 84 +++++ files/pt-br/web/api/document/index.html | 402 +++++++++++++++++++++ .../web/api/document/keydown_event/index.html | 178 +++++++++ .../web/api/document/keypress_event/index.html | 170 +++++++++ .../pt-br/web/api/document/keyup_event/index.html | 151 ++++++++ files/pt-br/web/api/document/location/index.html | 108 ++++++ files/pt-br/web/api/document/origin/index.html | 60 +++ .../web/api/document/queryselector/index.html | 107 ++++++ .../web/api/document/queryselectorall/index.html | 110 ++++++ files/pt-br/web/api/document/readystate/index.html | 102 ++++++ files/pt-br/web/api/document/referrer/index.html | 33 ++ files/pt-br/web/api/document/scripts/index.html | 84 +++++ files/pt-br/web/api/document/url/index.html | 19 + files/pt-br/web/api/document/write/index.html | 108 ++++++ files/pt-br/web/api/document/writeln/index.html | 43 +++ 47 files changed, 4321 insertions(+) create mode 100644 files/pt-br/web/api/document/activeelement/index.html create mode 100644 files/pt-br/web/api/document/alinkcolor/index.html create mode 100644 files/pt-br/web/api/document/anchors/index.html create mode 100644 files/pt-br/web/api/document/bgcolor/index.html create mode 100644 files/pt-br/web/api/document/body/index.html create mode 100644 files/pt-br/web/api/document/characterset/index.html create mode 100644 files/pt-br/web/api/document/close/index.html create mode 100644 files/pt-br/web/api/document/compatmode/index.html create mode 100644 files/pt-br/web/api/document/contenttype/index.html create mode 100644 files/pt-br/web/api/document/createelement/index.html create mode 100644 files/pt-br/web/api/document/createelementns/index.html create mode 100644 files/pt-br/web/api/document/currentscript/index.html create mode 100644 files/pt-br/web/api/document/defaultview/index.html create mode 100644 files/pt-br/web/api/document/designmode/index.html create mode 100644 files/pt-br/web/api/document/doctype/index.html create mode 100644 files/pt-br/web/api/document/document/index.html create mode 100644 files/pt-br/web/api/document/documentelement/index.html create mode 100644 files/pt-br/web/api/document/documenturi/index.html create mode 100644 files/pt-br/web/api/document/elementfrompoint/index.html create mode 100644 files/pt-br/web/api/document/elementoregistrado/index.html create mode 100644 files/pt-br/web/api/document/execcommand/index.html create mode 100644 files/pt-br/web/api/document/fullscreen/index.html create mode 100644 files/pt-br/web/api/document/getelementbyid/index.html create mode 100644 files/pt-br/web/api/document/getelementsbyclassname/index.html create mode 100644 files/pt-br/web/api/document/getelementsbyname/index.html create mode 100644 files/pt-br/web/api/document/getelementsbytagname/index.html create mode 100644 files/pt-br/web/api/document/getselection/index.html create mode 100644 files/pt-br/web/api/document/hasfocus/index.html create mode 100644 files/pt-br/web/api/document/head/index.html create mode 100644 files/pt-br/web/api/document/height/index.html create mode 100644 files/pt-br/web/api/document/images/index.html create mode 100644 files/pt-br/web/api/document/implementation/index.html create mode 100644 files/pt-br/web/api/document/importnode/index.html create mode 100644 files/pt-br/web/api/document/index.html create mode 100644 files/pt-br/web/api/document/keydown_event/index.html create mode 100644 files/pt-br/web/api/document/keypress_event/index.html create mode 100644 files/pt-br/web/api/document/keyup_event/index.html create mode 100644 files/pt-br/web/api/document/location/index.html create mode 100644 files/pt-br/web/api/document/origin/index.html create mode 100644 files/pt-br/web/api/document/queryselector/index.html create mode 100644 files/pt-br/web/api/document/queryselectorall/index.html create mode 100644 files/pt-br/web/api/document/readystate/index.html create mode 100644 files/pt-br/web/api/document/referrer/index.html create mode 100644 files/pt-br/web/api/document/scripts/index.html create mode 100644 files/pt-br/web/api/document/url/index.html create mode 100644 files/pt-br/web/api/document/write/index.html create mode 100644 files/pt-br/web/api/document/writeln/index.html (limited to 'files/pt-br/web/api/document') diff --git a/files/pt-br/web/api/document/activeelement/index.html b/files/pt-br/web/api/document/activeelement/index.html new file mode 100644 index 0000000000..c29692eaf3 --- /dev/null +++ b/files/pt-br/web/api/document/activeelement/index.html @@ -0,0 +1,164 @@ +--- +title: Document.activeElement +slug: Web/API/Document/activeElement +tags: + - API + - Document + - HTML DOM + - Property + - Reference +translation_of: Web/API/DocumentOrShadowRoot/activeElement +--- +

{{APIRef("DOM")}}

+ +

Retorna o {{ domxref("Element", "elemento") }} atualmente em foco, ou seja, o elemento que receberá os eventos do teclado caso o usuário digite algo. Esse atributo é somente-leitura.

+ +

Geralmente retorna um {{ HTMLElement("input") }} ou {{ HTMLElement("textarea") }}, caso esteja com uma seleção de texto ativa. Caso esteja, pode obter mais informações sobre a seleção utilizando as propriedades selectionStartselectionEnd. Caso o elemento em foco seja um {{ HTMLElement("select") }}(menu) ou {{ HTMLElement("input") }} do tipo button, checkbox ou radio.

+ +
Note: No Mac, elementos que nao sejam campos de texto geralmente não recebem foco.
+ +

Normalmente o usuário pode navegar entre os elementos que pode receber foco na página com o uso da tecla tab e ativar estes elementos com a tecla espaço (apertar um botão ou selecionar uma opção).

+ +

Não confunda foco com uma seleção de texto no documento, que consiste em sua maioria de nódos de texto estáticos. Veja {{ domxref("window.getSelection()") }}.

+ +

Quando não há nada selecionado, o activeElement da página é o {{ HTMLElement("body") }} ou null

+ +
+

Este atributo é parte da seção "Em desenvolvimento" da especificação do HTML 5.

+
+ +

Sintaxe

+ +
var curElement = document.activeElement;
+
+ +

Exemplo

+ +
<!DOCTYPE HTML>
+<html>
+<head>
+    <script type="text/javascript" charset="utf-8">
+    function init() {
+
+        function onMouseUp(e) {
+            console.log(e);
+            var outputElement = document.getElementById('output-element');
+            var outputText = document.getElementById('output-text');
+            var selectedTextArea = document.activeElement;
+            var selection = selectedTextArea.value.substring(
+            selectedTextArea.selectionStart, selectedTextArea.selectionEnd);
+            outputElement.innerHTML = selectedTextArea.id;
+            outputText.innerHTML = selection;
+        }
+
+        document.getElementById("ta-example-one").addEventListener("mouseup", onMouseUp, false);
+        document.getElementById("ta-example-two").addEventListener("mouseup", onMouseUp, false);
+    }
+    </script>
+</head>
+<body onload="init()">
+<div>
+    Select some text from one of the Textareas below:
+</div>
+<form id="frm-example" action="#" accept-charset="utf-8">
+<textarea name="ta-example-one" id="ta-example-one" rows="8" cols="40">
+This is Textarea Example One:
+Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec tincidunt, lorem a porttitor molestie, odio nibh iaculis libero, et accumsan nunc orci eu dui.
+</textarea>
+<textarea name="ta-example-two" id="ta-example-two" rows="8" cols="40">
+This is Textarea Example Two:
+Fusce ullamcorper, nisl ac porttitor adipiscing, urna orci egestas libero, ut accumsan orci lacus laoreet diam. Morbi sed euismod diam.
+</textarea>
+</form>
+Active Element Id: <span id="output-element"></span><br/>
+Selected Text: <span id="output-text"></span>
+
+</body>
+</html>
+
+ +

View on JSFiddle

+ +

Notas

+ +

Originalmente apresentada como extensão DOM proprietária no Internet Explorer 4, esta propriedade também é suportada no Opera e Safari (versão 4 ou maior)

+ +

Especificações

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'interaction.html#dom-document-activeelement', 'activeElement')}}{{Spec2('HTML WHATWG')}} 
+ +

Compatibilidade nos navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support23.04 [1]9.64.0
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

[1]: O IE9 tem um bug que ao tentar acessar o activeElement do {{domxref("window.parent")}} {{domxref("Document")}} de um {{HTMLElement("iframe")}}(i.e. parent.document.activeElement) é lançado um erro

+ +

Eventos relacionados

+ + diff --git a/files/pt-br/web/api/document/alinkcolor/index.html b/files/pt-br/web/api/document/alinkcolor/index.html new file mode 100644 index 0000000000..85d2bfaa77 --- /dev/null +++ b/files/pt-br/web/api/document/alinkcolor/index.html @@ -0,0 +1,36 @@ +--- +title: Document.alinkColor +slug: Web/API/Document/alinkColor +tags: + - Depreciado + - Propriedade + - Referencia +translation_of: Web/API/Document/alinkColor +--- +
{{APIRef("DOM")}}{{Deprecated_header}}
+ +

Retorna ou define a cor de um link ativo no corpo do documento. Um link está ativo durante o tempo entre os eventos mousedown e mouseup.

+ +

Sintaxe

+ +
var color = document.alinkColor;
+document.alinkColor = color;
+
+ +

color é uma string que contém o nome da cor (e.g., blue, darkblue, etc.) ou o valor hexadecimal da cor (e.g., #0000FF)

+ +

Notas

+ +

O valor padrão para esta propriedade no Mozilla Firefox é vermelho (#ee0000 em hexadecimal).

+ +

document.alinkColor está obsoleto em DOM Level 2 HTML. Uma alternativa é o seletor de CSS {{Cssxref(":active")}}.

+ +

Outra alternativa é document.body.aLink, embora tenha sido depreciado no HTML 4.01 a favor da alternativa CSS.

+ +

Gecko suporta ambos alinkColor/:active e {{Cssxref(":focus")}}. Suporte para Internet Explorer 6 e 7 alinkColor/:active apenas para HTML anchor (<a>) links e o comportamento é o mesmo que :focus sob Gecko. Não há suporte para :focus no IE.

+ +

Compatibilidade do navegador

+ + + +

{{Compat("api.Document.alinkColor")}}

diff --git a/files/pt-br/web/api/document/anchors/index.html b/files/pt-br/web/api/document/anchors/index.html new file mode 100644 index 0000000000..624c955b0e --- /dev/null +++ b/files/pt-br/web/api/document/anchors/index.html @@ -0,0 +1,107 @@ +--- +title: Document.anchors +slug: Web/API/Document/anchors +tags: + - API + - Deprecated + - HTML DOM + - NeedsCompatTable + - Property + - Reference +translation_of: Web/API/Document/anchors +--- +
{{APIRef("DOM")}}
+ +

{{deprecated_header("HTML5")}}

+ +

anchors retorna uma lista de todas as âncoras no documento.

+ +

Sintaxe

+ +
nodeList = document.anchors;
+
+ +

Exemplo

+ +
if ( document.anchors.length >= 5 ) {
+  dump("dump found too many anchors");
+  window.location = "http://www.google.com";
+}
+
+ +

O código a seguir é um exemplo que popula automaticamente um índice de conteúdo com cada âncora encontrada na página:

+ +
<!DOCTYPE html>
+<html lang="en">
+<head>
+<meta charset="UTF-8" />
+<title>Test</title>
+<script>
+function init() {
+  var toc = document.getElementById("toc");
+  var i, li, newAnchor;
+  for (i = 0; i < document.anchors.length; i++) {
+    li = document.createElement("li");
+    newAnchor = document.createElement('a');
+    newAnchor.href = "#" + document.anchors[i].name;
+    newAnchor.innerHTML = document.anchors[i].text;
+    li.appendChild(newAnchor);
+    toc.appendChild(li);
+  }
+}
+</script>
+
+</head>
+<body onload="init()">
+
+<h1>Title</h1>
+<h2><a name="contents">Contents</a></h2>
+<ul id="toc"></ul>
+
+<h2><a name="plants">Plants</a></h2>
+<ol>
+    <li>Apples</li>
+    <li>Oranges</li>
+    <li>Pears</li>
+</ol>
+
+<h2><a name="veggies">Veggies</a></h2>
+<ol>
+    <li>Carrots</li>
+    <li>Celery</li>
+    <li>Beats</li>
+</ol>
+
+</body>
+</html>
+
+ +

View on JSFiddle

+ +

Notas

+ +

Por motivos de compatibilidade, o conjunto de âncoras retornadas por anchors contém apenas as âncoras criadas com o atributo name, não incluindo as âncoras criadas com o atributo {{ htmlattrxref("id") }}.

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-document-anchors', 'Document.anchors')}}{{ Spec2('HTML WHATWG') }}Obsoleted.
{{SpecName('DOM2 HTML', 'html.html#ID-7577272', 'Document.anchors')}}{{ Spec2('DOM2 Events') }}Initial definition.
diff --git a/files/pt-br/web/api/document/bgcolor/index.html b/files/pt-br/web/api/document/bgcolor/index.html new file mode 100644 index 0000000000..66ec8d48ca --- /dev/null +++ b/files/pt-br/web/api/document/bgcolor/index.html @@ -0,0 +1,35 @@ +--- +title: Document.bgColor +slug: Web/API/Document/bgColor +tags: + - Obsoleto + - Propriedade + - Referencia +translation_of: Web/API/Document/bgColor +--- +

{{APIRef("DOM")}} {{ Deprecated_header() }}

+ +

A propriedade obsoleta bgColor obtém ou atribue a cor de fundo do documento atual.

+ +

Sintaxe

+ +
color = document.bgColor
+document.bgColor = color
+
+ +

Parâmetros

+ + + +

Exemplo

+ +
document.bgColor = "darkblue";
+
+ +

Notas

+ +

O valor padrão para esta propriedade no Firefox é branco (#ffffff em hexadecimal).

+ +

document.bgColor está obsoleto no DOM Level 2 HTML. A alternativa recomendada é fazer uso do atributo CSS {{Cssxref("background-color")}} que pode ser acessado através do DOM com document.body.style.backgroundColor. Uma outra alternativa é o document.body.bgColor, apesar dessa também estar obsoleta no HTML 4.01 em funcão da alternativa do CSS.

diff --git a/files/pt-br/web/api/document/body/index.html b/files/pt-br/web/api/document/body/index.html new file mode 100644 index 0000000000..cb21522c4f --- /dev/null +++ b/files/pt-br/web/api/document/body/index.html @@ -0,0 +1,44 @@ +--- +title: Document.body +slug: Web/API/Document/body +translation_of: Web/API/Document/body +--- +
{{APIRef("DOM")}}
+ +

Retorna o elemento {{HTMLElement("body")}} ou o {{HTMLElement("frameset")}} do documento atual, ou null se nenhum destes elementos existir.

+ +

Sintaxe

+ +
var objRef = document.body;
+document.body = objRef;
+ +

Exemplo

+ +
// No HTML: <body id="oldBodyElement"></body>
+alert(document.body.id); // "oldBodyElement"
+
+var aNewBodyElement = document.createElement("body");
+
+aNewBodyElement.id = "newBodyElement";
+document.body = aNewBodyElement;
+alert(document.body.id); // "newBodyElement"
+
+ +

Notas

+ +

document.body é o elemento que envolve o conteúdo do documento. Em documentos com conteúdo no <body>, retorna o elemento <body>, e em documentos que usam frameset, retorna o elemento <frameset> mais periférico.

+ +

Apesar do body ser configurável, definir um novo body em um documento irá remover todos os elementos contidos no elemento <body> existente.

+ +

Especificação

+ + + +

Veja Também

+ + diff --git a/files/pt-br/web/api/document/characterset/index.html b/files/pt-br/web/api/document/characterset/index.html new file mode 100644 index 0000000000..30ec060745 --- /dev/null +++ b/files/pt-br/web/api/document/characterset/index.html @@ -0,0 +1,65 @@ +--- +title: Document.characterSet +slug: Web/API/Document/characterSet +tags: + - Documento + - Propriedade + - Referencia +translation_of: Web/API/Document/characterSet +--- +
{{ ApiRef("DOM") }}
+ +
A propriedade somente leitura Document.characterSet retorna a character encoding(codificação de caracteres) do documento com o qual ele é renderizado atualmente. (Uma codificação de caracteres é um conjunto de caracteres e como interpretar bytes nesses caracteres.)
+ +
+ +
+

Um “character set”(conjunto de caracteres) e “character encoding”(codificação de caracteres) estão relacionados, mas diferentes. Apesar do nome dessa propriedade, ela retorna a codificação.

+
+ +

Usuários podem sobrepor a codificação especificada pelo desenvolvedor dentro do cabeçalho Content-Type (tipo de conteúdo) ou embutida como <meta charset = "utf-8">, como no menu Exibir → Codificacao de Texto Essa substituição é fornecida para corrigir codificações especificadas pelo desenvolvedor incorretas que resultam em texto ilegivel.

+ +
+

As propriedades document.charset e document.inputEncoding são aliases legados para document.characterSet. Não use mais eles.

+
+ +

Sintaxe

+ +
var string = document.characterSet;
+ +

Exemplos

+ +
<button onclick="console.log(document.characterSet);">
+  Registro de Codificacao de Caracteres
+</button>
+<!-- mostra a codificacao de caracteres do documento no console do desevolvedor, como "ISO-8859-1" ou "UTF-8" -->
+
+ +

Especificações

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-document-characterset', 'characterSet')}}{{Spec2('DOM WHATWG')}} +

Definição Inicial.

+
+ +

Compatibilidade do navegador

+ + + +

{{Compat("api.Document.characterSet")}}

diff --git a/files/pt-br/web/api/document/close/index.html b/files/pt-br/web/api/document/close/index.html new file mode 100644 index 0000000000..7c9b110edd --- /dev/null +++ b/files/pt-br/web/api/document/close/index.html @@ -0,0 +1,27 @@ +--- +title: Document.close() +slug: Web/API/Document/close +translation_of: Web/API/Document/close +--- +

{{APIRef("DOM")}}

+ +

O metodo document.close() termina a gravação em um documento, aberto com  document.open().

+ +

Sintaxe

+ +
document.close();
+
+ +

Exemplo

+ +
// abre um documento e escreve nele.
+// escreve o conteúdo no documento.
+// fecha o documento.
+document.open();
+document.write("<p>O primeiro e unico conteúdo.</p>");
+document.close();
+
+ +

Especificação

+ +

DOM Level 2 HTML: close() Method

diff --git a/files/pt-br/web/api/document/compatmode/index.html b/files/pt-br/web/api/document/compatmode/index.html new file mode 100644 index 0000000000..1ca33ff573 --- /dev/null +++ b/files/pt-br/web/api/document/compatmode/index.html @@ -0,0 +1,42 @@ +--- +title: Document.compatMode +slug: Web/API/Document/compatMode +translation_of: Web/API/Document/compatMode +--- +

{{ ApiRef("DOM") }}

+ +

Indica se o documento está renderizado no Quirks mode ou no modo dos Padrões.

+ +

Sintaxe

+ +
modo = document.compatMode
+
+ +

Valores

+ + + +
+
modo
+
É um valor enumerado que pode ser:
+
+ +
+

Nota: todos estes modos agora são definidos em padrões, então os antigos nomes "standards" e "almost standards" são sem sentido, e portanto não são mais usados nos padrões.

+
+ +

Exemplo

+ +
if (document.compatMode == "BackCompat") {
+  // in Quirks mode
+}
+
+ +

Especificações

+ + diff --git a/files/pt-br/web/api/document/contenttype/index.html b/files/pt-br/web/api/document/contenttype/index.html new file mode 100644 index 0000000000..5d29907089 --- /dev/null +++ b/files/pt-br/web/api/document/contenttype/index.html @@ -0,0 +1,46 @@ +--- +title: Document.contentType +slug: Web/API/Document/contentType +translation_of: Web/API/Document/contentType +--- +
{{APIRef}}
+ +

Document.contentType é uma propriedade somente de leitura, que retorna o tipo MIME do documento que esta sendo rendenrizado.Isso pode vir de cabeçalhos HTPP ou de outras fontes de informações MIME, e pode se afetado por conversões realizadas pelo navegador ou pelas extenções.

+ +
+

Note: Esta proiedade não é afetada pelos elementos {{HTMLElement("meta")}}.

+
+ +

Sintaxe

+ +
contentType = document.contentType;
+
+ +

Value

+ +

contentType é uma propriedade somente de leitura.

+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('DOM WHATWG', '#dom-document-contenttype', 'Document.contentType')}}{{Spec2('DOM WHATWG')}}Definição inicial
+ +

Compatibilidade com os navegadores

+ + + +
{{Compat("api.Document.contentType")}}
diff --git a/files/pt-br/web/api/document/createelement/index.html b/files/pt-br/web/api/document/createelement/index.html new file mode 100644 index 0000000000..3cb88ecb37 --- /dev/null +++ b/files/pt-br/web/api/document/createelement/index.html @@ -0,0 +1,82 @@ +--- +title: Document.createElement() +slug: Web/API/Document/createElement +tags: + - Documento + - Referencia + - Referência(2) + - metodo +translation_of: Web/API/Document/createElement +--- +
{{APIRef("DOM")}}
+ +
 
+ +

Em um documento HTML, o método Document.createElement() cria o elemento HTML especificado ou um {{domxref("HTMLUnknownElement")}} se o nome do elemento dado não for conhecido.

+ +

Em um documento XUL, o elemento XUL especificado é criado.

+ +

Em outros documentos, ele cria um elemento com um namespace URI null.

+ +

Sintaxe

+ +
var elemento = document.createElement(nomeDaTag);
+
+ + + +

Exemplo

+ +

Este código cria uma nova <div> e a insere antes do elemento com ID "div1".

+ +

HTML

+ +
<!DOCTYPE html>
+<html>
+<head>
+  <title>||Trabalhando com elementos||</title>
+</head>
+<body>
+  <div id="div1">O texto acima foi criado dinamicamente.</div>
+</body>
+</html>
+
+ +

JavaScript

+ +
document.body.onload = adcElemento;
+
+function adcElemento () {
+  // cria um novo elemento div
+  // e dá à ele conteúdo
+  var divNova = document.createElement("div");
+  var conteudoNovo = document.createTextNode("Olá, cumprimentos!");
+  divNova.appendChild(conteudoNovo); //adiciona o nó de texto à nova div criada
+
+  // adiciona o novo elemento criado e seu conteúdo ao DOM
+  var divAtual = document.getElementById("div1");
+  document.body.insertBefore(divNova, divAtual);
+}
+ +

{{EmbedLiveSample("Exemplo", 500, 50)}}

+ +

Notas

+ + + +

Especificações

+ + diff --git a/files/pt-br/web/api/document/createelementns/index.html b/files/pt-br/web/api/document/createelementns/index.html new file mode 100644 index 0000000000..ece55f592e --- /dev/null +++ b/files/pt-br/web/api/document/createelementns/index.html @@ -0,0 +1,90 @@ +--- +title: Document.createElementNS() +slug: Web/API/Document/createElementNS +tags: + - API + - DOM + - Referencia + - metodo +translation_of: Web/API/Document/createElementNS +--- +
{{ApiRef("DOM")}}
+ +

Creates an element with the specified namespace URI and qualified name.

+ +

Cria um elemento com Namespace URI e nome qualificado, como especificado.

+ +

Syntax

+ +
element = document.createElementNS(namespaceURI, qualifiedName);
+
+ + + +

Namespace URI's válidos

+ + + +

Exemplo

+ +

Isso cria um novo elemento <div> no namespace XHTML e anexa ele ao elemento vbox. Embora isso não seja um documento XUL extremamente útil, pode demonstrar o uso de elementos de dois namespaces diferentes em apenas um documento:

+ +
<?xml version="1.0"?>
+<page xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
+      xmlns:html="http://www.w3.org/1999/xhtml"
+      title="||Working with elements||"
+      onload="init()">
+
+<script type="text/javascript"><![CDATA[
+ var container;
+ var newdiv;
+ var txtnode;
+
+ function init(){
+   container = document.getElementById("ContainerBox");
+   newdiv = document.createElementNS("http://www.w3.org/1999/xhtml","div");
+   txtnode = document.createTextNode("Este é o texto construído dinâmicamente com createElementNS e createTextNode então é inserido no documento usando appendChild.");
+   newdiv.appendChild(txtnode);
+   container.appendChild(newdiv);
+ }
+
+]]></script>
+
+ <vbox id='ContainerBox' flex='1'>
+  <html:div>
+   O script desta página irá colocar conteúdo dinâmico abaixo:
+  </html:div>
+ </vbox>
+
+</page>
+
+ +

Notas

+ +

O exemplo dado anteriormente usa script inline que não é recomendado em documentos XHTML. Este exemplo particular é atualmente um documento  XUL com XHTML incorporado, contudo, a recomendação ainda se aplica. scripts Inline  não causam nenhum problema neste pequeno exemplo, contudo, para qualquer trabalho sério você precisa ler sobre Uso correto de CSS e JavaScript en documentos XHTML.

+ +

Para criar um elemento sem especificar seu namespace URI, use o método createElement.

+ +

Especificação

+ + + +

Veja também

+ + diff --git a/files/pt-br/web/api/document/currentscript/index.html b/files/pt-br/web/api/document/currentscript/index.html new file mode 100644 index 0000000000..179c950916 --- /dev/null +++ b/files/pt-br/web/api/document/currentscript/index.html @@ -0,0 +1,99 @@ +--- +title: Document.currentScript +slug: Web/API/Document/currentScript +translation_of: Web/API/Document/currentScript +--- +
{{ ApiRef("DOM") }}
+ +
 
+ +

Retorna o elemento que está sendo processado atualmente.

+ +

Sintaxe

+ +
var curScriptElement = document.currentScript;
+
+ +

Exemplo

+ +

O exemplo abaixo verifica se o script está sendo executado de forma assíncrona:

+ +
if (document.currentScript.async) {
+  console.log("Execução assíncrona");
+} else {
+  console.log("Execução síncrona");
+}
+ +

View Live Examples

+ +

Nota

+ +

Se o código estiver sendo chamado como um callback ou manipulador de eventos, ele não irá referenciar o  elemento; a referência ao elemento só acontece quando ele está sendo processado inicialmente.

+ +

Compatibilidade nos navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte Básico29{{ CompatGeckoDesktop("2.0") }}{{ CompatNo() }} (as of IE11)16 +

+
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte Básico4.4{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{ CompatUnknown() }}{{ CompatUnknown() }}iOS 8
+
+ +

Especificações

+ + + +

Veja também

+ + diff --git a/files/pt-br/web/api/document/defaultview/index.html b/files/pt-br/web/api/document/defaultview/index.html new file mode 100644 index 0000000000..77ed7a4c72 --- /dev/null +++ b/files/pt-br/web/api/document/defaultview/index.html @@ -0,0 +1,28 @@ +--- +title: Document.defaultView +slug: Web/API/Document/defaultView +translation_of: Web/API/Document/defaultView +--- +
{{ ApiRef() }}
+ +

Sumário

+ +

Em navegadores, retorna o objeto window associado ao documento ou null se não houver.

+ +

Sintaxe

+ +
var win = document.defaultView;
+ +

Esta propriedade é de somente-leitura.

+ +

Notas

+ +

De acordo com o quirksmode, defaultView não é suportado no IE até o IE 9.

+ +

Especificação

+ + diff --git a/files/pt-br/web/api/document/designmode/index.html b/files/pt-br/web/api/document/designmode/index.html new file mode 100644 index 0000000000..b2c070008b --- /dev/null +++ b/files/pt-br/web/api/document/designmode/index.html @@ -0,0 +1,104 @@ +--- +title: Document.designMode +slug: Web/API/Document/designMode +translation_of: Web/API/Document/designMode +--- +
{{ ApiRef() }}
+ +
 
+ +

Sumário

+ +

document.designMode controla se o documento todo é editável. Valores validos são "on" e "off". De acordo com a especificação, esta propriedade é por padrão "off". Firefox segue este padrão. Nas versões anteriores do Chrome e IE o padrão é "inherit". No IE6-10, o valor é capitalizado.

+ +

Sintaxe

+ +
var mode = document.designMode;
+document.designMode = "on";
+document.designMode = "off";
+ +

Exemplo

+ +

Cria um documento {{HTMLElement("iframe")}} editável:

+ +
iframe_node.contentDocument.designMode = "on";
+
+ +

Especificação

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#making-entire-documents-editable:-the-designmode-idl-attribute', 'designMode')}}{{Spec2('HTML WHATWG')}}Initial definition.
+ +

Compatibilidade nos Browsers

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

 

+ +

Veja também:

+ + diff --git a/files/pt-br/web/api/document/doctype/index.html b/files/pt-br/web/api/document/doctype/index.html new file mode 100644 index 0000000000..72a731c314 --- /dev/null +++ b/files/pt-br/web/api/document/doctype/index.html @@ -0,0 +1,59 @@ +--- +title: Document.doctype +slug: Web/API/Document/doctype +translation_of: Web/API/Document/doctype +--- +
{{ApiRef("DOM")}}
+ +

Retorna a declaração do tipo de documento(Document Type Declaration (DTD)) associado ao documento atual. O objeto retornado implementa a interface {{domxref("DocumentType")}}. Use {{domxref("DOMImplementation.createDocumentType()")}} para criar um DocumentType.

+ +

Sintaxe

+ +
doctype = document.doctype;
+
+ + + +

Exemplo

+ +
var doctypeObj = document.doctype;
+
+console.log(
+  "doctypeObj.name: "           + doctypeObj.name            + "\n" +
+  "doctypeObj.internalSubset: " + doctypeObj.internalSubset  + "\n" +
+  "doctypeObj.publicId: "       + doctypeObj.publicId        + "\n" +
+  "doctypeObj.systemId: "       + doctypeObj.systemId
+);
+ +

Notas

+ +

A propriedade retornará null se não houvernehum  DTD associado ao documento atual.

+ +

O nível 2 do DOM não suporta a edição da declaração do tipo de documento.

+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('DOM WHATWG', '#dom-document-doctype', 'Document: doctype')}}{{Spec2('DOM WHATWG')}}
+ +

 Compatibilidade com os navegadores

+ + + +

{{Compat("api.Document.doctype")}}

diff --git a/files/pt-br/web/api/document/document/index.html b/files/pt-br/web/api/document/document/index.html new file mode 100644 index 0000000000..3152137704 --- /dev/null +++ b/files/pt-br/web/api/document/document/index.html @@ -0,0 +1,87 @@ +--- +title: Document() +slug: Web/API/Document/Document +translation_of: Web/API/Document/Document +--- +

{{APIRef}}{{Non-standard_header}}

+ +

O construtor Document cria um novo objeto {{domxref("Document")}},  o qual trata de uma página carregada no navegador servindo como porta de entrada para o conteúdo da página.

+ +

Sintaxe

+ +
var document = new Document()
+ +

Parâmetros

+ +

Nenhum.

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('DOM WHATWG','#interface-document','Document')}}{{Spec2('DOM WHATWG')}}Definição inicial
+ +

Compatibilidade com Navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
NavegadorChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte{{CompatChrome(60)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOpera(47)}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
NavegadorAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Suporte{{CompatChrome(60)}}{{CompatChrome(60)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOperaMobile(47)}}{{CompatUnknown}}
+
diff --git a/files/pt-br/web/api/document/documentelement/index.html b/files/pt-br/web/api/document/documentelement/index.html new file mode 100644 index 0000000000..869cd7a75d --- /dev/null +++ b/files/pt-br/web/api/document/documentelement/index.html @@ -0,0 +1,43 @@ +--- +title: Document.documentElement +slug: Web/API/Document/documentElement +tags: + - Propriedade + - Referencia + - raiz +translation_of: Web/API/Document/documentElement +--- +

{{ ApiRef("DOM") }}

+ +

O  document.documentElement  retorna o Elemento que é o elemento raiz do documento (por exemplo, o elemento <html> para documentos HTML).

+ +

Sintaxe

+ +
var element = document.documentElement;
+
+ +

Exemplo

+ +
var rootElement = document.documentElement;
+var primeiroNivel = rootElement.childNodes;
+
+// primeiroNivel é a NodeList do filho direto do elemento raíz
+for (var i = 0; i < primeiroNivel.length; i++) {
+   // faça algo com cada filho direto do elemento raiz
+   // como primeiroNivel[i]
+
+}
+ +

Notas

+ +

Esta propriedade é uma conveniência somente leitura para obter o elemento raiz associado com qualquer documento.

+ +

Documentos HTML tipicamente contém somente um único nó filho, <html>, talvez com uma declaração DOCTYPE antes dele. Documentos XML, frequentemete contêm múltiplos nós filhos: o elemento de raiz, a declaração DOCTYPE, e as instruções de processamento.

+ +

É por isso que você deve usar document.documentElement em vez de {{Domxref ("document.firstChild")}} para obter o elemento raiz.

+ +

Especificações

+ + diff --git a/files/pt-br/web/api/document/documenturi/index.html b/files/pt-br/web/api/document/documenturi/index.html new file mode 100644 index 0000000000..52609f2bd5 --- /dev/null +++ b/files/pt-br/web/api/document/documenturi/index.html @@ -0,0 +1,53 @@ +--- +title: Document.documentURI +slug: Web/API/Document/documentURI +translation_of: Web/API/Document/documentURI +--- +
{{ApiRef("DOM")}}
+ +
A propiedade documentURI da interface {{domxref("Document")}} retorna uma string com a localização de um documento.
+ +
+ +
Na definição original DOM3 documentURI é um atributo de leitura/escrita.No padrão mais recente DOM4 é somente de leitura.
+ +

Sintaxe

+ +
var string = document.documentURI;
+
+ +

Notas

+ +

Os Documentos HTML tem uma propriedade {{domxref("document.URL")}} que retorna o mesmo valor (localização do documento).

+ +

A diferençã é que document.URL só pode ser usado em documentos HTML, enquanto documentURI está disponivel para todos os documentos web.

+ +

Specificações

+ + + + + + + + + + + + + + + + + + + + + +
SpecificaçãoStatusComentário
{{SpecName('DOM WHATWG', '#dom-document-documenturi','documentURI')}}{{Spec2('DOM WHATWG')}}
{{SpecName('DOM3 Core', '#Document3-documentURI', 'documentURI')}}{{Spec2('DOM3 Core')}}Initial definition
+ +

Compatibilidade de navegadores

+ + + +

{{Compat("api.Document.documentURI")}}

diff --git a/files/pt-br/web/api/document/elementfrompoint/index.html b/files/pt-br/web/api/document/elementfrompoint/index.html new file mode 100644 index 0000000000..ce447f2830 --- /dev/null +++ b/files/pt-br/web/api/document/elementfrompoint/index.html @@ -0,0 +1,132 @@ +--- +title: Document.elementFromPoint() +slug: Web/API/Document/elementFromPoint +tags: + - API + - CSSOM View + - Method + - NeedsMarkupWork + - NeedsMobileBrowserCompatibility + - Reference +translation_of: Web/API/DocumentOrShadowRoot/elementFromPoint +--- +
{{APIRef("DOM")}}
+ +

O método elementFromPoint() da interface {{domxref("Document")}} retorna o elemento de maior nível nas coordenadas especificadas.

+ +

Se o elemento no ponto especificado pertencer à outro documento (por exemplo, um subdocumento em um iframe), será retornado o pai do subdocumento (o próprio iframe). Se o elemento em determinado ponto for anônimo ou for um conteudo gerado por XBL, como por exemplo barras de scroll de caixas de texto, então será retornado o primeiro elemento pai, não-anônimo (por exemplo, a própria caixa de texto).

+ +

Se o ponto especificado estiver fora dos limites visíveis do documento ou tiver uma coordenada negativa, o resultado é null.

+ +

Se você precisa encontrar uma posição específica dentro do elemento, use {{domxref("Document.caretPositionFromPoint()")}}.

+ +

{{Note("Chamados por documentos XUL devem esperar até o evento onload ser acionado antes de chamar este método.")}}

+ +

Sintaxe

+ +
var element = document.elementFromPoint(x, y);
+ +

Parâmetros

+ +
+
x
+
Uma posição horizontal dentro do viewport atual.
+
y
+
Uma position vertical dentro do viewport atual.
+
+ +

Valor retornado

+ +

O objeto de nível mais alto {{domxref("Element")}} dentro das coordenadas declaradas.

+ +

Exemplo

+ +
<!DOCTYPE html>
+<html lang="en">
+<head>
+<title>exemplo de elementFromPoint</title>
+
+<script>
+function changeColor(newColor) {
+  elem = document.elementFromPoint(2, 2);
+  elem.style.color = newColor;
+}
+</script>
+</head>
+
+<body>
+<p id="para1">Algum texto aqui</p>
+<button onclick="changeColor('blue');">azul</button>
+<button onclick="changeColor('red');">vermelho</button>
+</body>
+</html>
+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComment
{{SpecName('CSSOM View', '#dom-document-elementfrompoint', 'elementFromPoint')}}{{Spec2('CSSOM View')}}Definição Inicial.
+ +

Compatibilidade entre navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support {{CompatChrome(4.0)}}35.510.50{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidChrome para AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
diff --git a/files/pt-br/web/api/document/elementoregistrado/index.html b/files/pt-br/web/api/document/elementoregistrado/index.html new file mode 100644 index 0000000000..bff318b3a9 --- /dev/null +++ b/files/pt-br/web/api/document/elementoregistrado/index.html @@ -0,0 +1,132 @@ +--- +title: Document.registerElement() +slug: Web/API/Document/ElementoRegistrado +tags: + - DOM + - Document.registerElement() + - ELEMENTO DOM + - Web Components + - registerElement +translation_of: Web/API/Document/registerElement +--- +

{{APIRef("DOM")}}

+ +
+

Note:document.registerElement() está depreciado em favor do customElements.define().

+
+ +

O método document.registerElement() registra um novo elemento personalizado no browser e returna um construtor para o novo elemento.

+ +
+

Nota: Esta é uma tecnologia experimental. O browser você precisa usar suporte à componentes web. Veja Habilitando componentes web no Firefox.

+
+ +

Sintaxe

+ +
var constructor = document.registerElement(tag-name, options);
+ +

Parâmetros

+ +
+
tag-name
+
O nome do elemento personalizado. O nome precisa conter um dash (-), por exemplo minha-tag.
+
Opções{{optional_inline}}
+
+

Um projeto com propriedades protótipo como base para o elememento personalizado, e extends, uma existente tag para estender. Ambos são opcionais.

+
+
+ +

Exemplo

+ +

Aqui é um exemplo muito simples:

+ +
var Mytag = document.registerElement('my-tag');
+
+ +

Agora as novas tags são registradas no browser.

+ +

Uma variável Mytag tem um construtor que você pode usar para criar um elemento my-tag nos documentos como seguem:

+ +
document.body.appendChild(new Mytag());
+ +

Isto insere um elemento vazio my-tag que será visível se você usar o browser para desenvolvedores. Isto não será visível se você usar a ferramenta visão da capacidade do código fonte do browser. E isto não será visível no browser a menos que você adicione alguns conteúdos para a tag. Aqui está um caminho para adicionar conteúdo a nova tag:

+ +
var mytag = document.getElementsByTagName("my-tag")[0];
+mytag.textContent = "I am a my-tag element.";
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('Custom Elements')}}{{Spec2('Custom Elements')}} +

definição inicial

+
+ +

Compatibilidade do Browser

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico3531[1]{{CompatNo}}25{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico4.4.431[1]{{CompatNo}}25{{CompatNo}}
+
+ +

[1] Esta API é implementada uma preferência

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/document/execcommand/index.html b/files/pt-br/web/api/document/execcommand/index.html new file mode 100644 index 0000000000..cc5e3d3da8 --- /dev/null +++ b/files/pt-br/web/api/document/execcommand/index.html @@ -0,0 +1,174 @@ +--- +title: Document.execCommand() +slug: Web/API/Document/execCommand +translation_of: Web/API/Document/execCommand +--- +
{{ApiRef("DOM")}}{{Obsolete_header}}
+ +

Quando um documento HTML está em designMode, seu objeto document  expõe um metodo execCommand para editar a região editável corrente, algo como elementos form inputs ou contentEditable.

+ +

A maioria dos comandos afetam apaenas uma área selecionada [seleção] (negrito, itálico, etc.), enquantos outros adicionam novos elementos (adicionar um link por exemplo), ou afetam uma linha toda (identação). Quando usando contentEditable, o metódo execCommand() afeta o elemento editável ativo.

+ +

Síntaxe

+ +
document.execCommand(aCommandName, aShowDefaultUI, aValueArgument)
+
+ +

Valor de Retorno

+ +

Um {{jsxref('Boolean')}} que tem valor false se o comando não é válido ou está desabilitado.

+ +
+

Nota: Retorna true se for parte da interação do usuário. Não tente utilizar o retorno para verificar o suporte do browser antes de chamar o comando.

+
+ +

Parâmetros

+ +
+
aCommandName
+
Uma {{domxref("DOMString")}} especificando o nome do comando a ser executado. Veja {{anch("Comandos")}} para um lista dos possíveis comandos.
+
aShowDefaultUI
+
Um {{jsxref("Boolean")}} indicando se a interface padrão do usuário deve ser mostrada. Isso não é implementado no Mozilla.
+
aValueArgument
+
Para comandos que requerem um argumento de entrada. É uma {{domxref("DOMString")}} provendo a informação. Por exemplo, insertImage requer uma URL da imagem a ser inserida. Use null se nenhum argumento é necessário.
+
+ +

Comandos

+ +
+
backColor
+
Muda a cor de fundo do documento. No modo styleWithCss, ele afeta a cor de fundo do bloco que contém. Isso requer um valor de {{cssxref("<color>")}} passado como argumento. Observe que o Internet Explorer usa isso para definir a cor do plano de fundo do texto.
+
bold
+
Ativa / desativa negrito na seleção ou no ponto de inserção. O Internet Explorer usa a tag {{HTMLElement("strong")}} no lugar de {{HTMLElement("b")}}.
+
ClearAuthenticationCache
+
Limpa todas as credenciais de autenticação do cache.
+
contentReadOnly
+
Torna o documento de conteúdo somente leitura ou editável. Isso requer um valor booleano true / false como argumento. (Não é suportado pelo Internet Explorer.)
+
copy
+
Copia a seleção atual para a área de transferência. As condições para ativar esse comportamento variam de um navegador para outro e evoluíram com o tempo. Verifique a Tabela de {{anch("Compatibilidade entre Browsers")}} para determinar se você pode usar no seu caso.
+
createLink
+
Cria um hiperlink a partir da seleção, mas apenas se houver uma seleção. Requer uma string URI como argumento para o href do link.  O URI deve conter pelo menos um único caractere, que pode ser um espaço em branco. (O Internet Explorer criará um link com um valor nulo.)
+
cut
+
Remove a seleção atual e a copia para a área de transferência. Quando esse comportamento é ativado, varia entre os navegadores e suas condições evoluíram com o tempo. Verifique a Tabela de {{anch("Compatibilidade entre Browsers")}} para mais detalhes.
+
decreaseFontSize
+
Adiciona a tag {{HTMLElement("small")}} ao redor da seleção ou no ponto de inserção. (Não é suportado pelo Internet Explorer.)
+
defaultParagraphSeparator
+
Altera o separador de parágrafos usado quando novos parágrafos são criados em regiões de texto editáveis. Veja Diferenças na geração de marcação para mais detalhes.
+
delete
+
Exclui o conteúdo da seleção atual.
+
enableAbsolutePositionEditor
+
Habilita ou desabilita a garra que permite mover elementos absolutamente posicionados. Está desabilitado por padrão no Firefox 63 Beta / Dev Edition ({{bug(1449564)}})
+
enableInlineTableEditing
+
Ativa ou desativa os controles de inserção e exclusão de linhas / colunas da tabela. Está desabilitado por padrão no Firefox 63 Beta / Dev Edition ({{bug(1449564)}}).
+
enableObjectResizing
+
Ativa ou desativa as alças de redimensionamento em imagens, tabelas e elementos absolutamente posicionados e outros objetos redimensionáveis. Está desabilitado por padrão no Firefox 63 Beta / Dev Edition ({{bug(1449564)}}).
+
fontName
+
Altera o nome da fonte para a seleção ou no ponto de inserção. Isso requer uma string com o nome da fonte (como "Arial") como argumento.
+
fontSize
+
Altera o tamanho da fonte para a seleção ou no ponto de inserção. Isso requer um número inteiro de 1-7 como argumento.
+
foreColor
+
Altera a cor da fonte para a seleção ou no ponto de inserção. Isso requer uma string de cor (hexadecimal) como argumento.
+
formatBlock
+
Adiciona um elemento de nível de bloco HTML ao redor da linha que contém a seleção atual, substituindo o elemento de bloco que contém a linha, se houver (no Firefox,  {{HTMLElement("blockquote")}} é a exceção - envolverá qualquer elemento de bloco que contenha). Requer uma sequência de nome de tag como argumento de valor. Praticamente todos os elementos em nível de bloco podem ser usados. (Internet Explorer e Edge suportam apenas tags de cabeçalho  H1H6, ADDRESS, e PRE, que devem estar entre colchetes angulares, como "<H1>".)
+
forwardDelete
+
Exclui o caractere depois da posição do cursor, idêntico a pressionar a tecla Delete em um teclado do Windows.
+
heading
+
Adiciona um elemento de cabeçalho ao redor de uma linha de seleção ou ponto de inserção. Requer uma string com o nome da tag como argumento (ex. "H1", "H6"). (Não suportado pelo Internet Explorer e Safari.)
+
hiliteColor
+
Altera a cor do plano de fundo para a seleção ou no ponto de inserção. Requer uma sequência de valores de cores como argumento. useCSS tem de ser true para essa função. (Não é suportado pelo Internet Explorer.)
+
increaseFontSize
+
Adiciona uma tag {{HTMLElement("big")}} ao redor da seleção ou no ponto de inserção. (Não é suportado pelo Internet Explorer.)
+
indent
+
Recua a linha que contém o ponto de seleção ou inserção. No Firefox, se a seleção abranger várias linhas em diferentes níveis de recuo, apenas as linhas menos recuadas na seleção serão recuadas.
+
insertBrOnReturn
+
Controla se a tecla Enter insere um elemento {{HTMLElement("br")}}, ou divide o elemento do bloco atual em dois. (Não é suportado pelo Internet Explorer.)
+
insertHorizontalRule
+
Insere um elemento {{HTMLElement("hr")}} no ponto de inserção ou substitui a seleção por ele.
+
insertHTML
+
Insere uma string HTML no ponto de inserção (exclui a seleção). Requer uma string HTML válida como argumento. (Não é suportado pelo Internet Explorer.)
+
insertImage
+
Insere uma imagem no ponto de inserção (exclui a seleção). Requer uma string de URL para o src da imagem como argumento. Os requisitos para essa string são os mesmos que createLink.
+
insertOrderedList
+
Cria uma lista ordenada e numerada para a seleção ou no ponto de inserção.
+
insertUnorderedList
+
Cria uma lista não ordenada para a seleção ou no ponto de inserção.
+
insertParagraph
+
Insere um parágrafo ao redor da seleção ou da linha atual. (O Internet Explorer insere um parágrafo no ponto de inserção e exclui a seleção.)
+
insertText
+
Insere o texto fornecido no ponto de inserção (exclui a seleção).
+
italic
+
Ativa / desativa o itálico para a seleção ou no ponto de inserção. (O Internet Explorer usa o elemento {{HTMLElement("em")}} no lugar de {{HTMLElement("i")}}.)
+
justifyCenter
+
Centraliza o ponto de seleção ou inserção.
+
justifyFull
+
Justifica o ponto de seleção ou inserção.
+
justifyLeft
+
Justifica o ponto de seleção ou inserção à esquerda.
+
justifyRight
+
Justifica à direita a seleção ou o ponto de inserção.
+
outdent
+
Supera a linha que contém o ponto de seleção ou inserção.
+
paste
+
Cola o conteúdo da área de transferência no ponto de inserção (substitui a seleção atual). Desativado para conteúdo da web. Veja [1].
+
redo
+
Refaz o comando desfazer anterior.
+
removeFormat
+
Remove toda a formatação da seleção atual.
+
selectAll
+
Seleciona todo o conteúdo da região editável.
+
strikeThrough
+
Ativa / desativa o strikethrough(linha riscada) para a seleção ou no ponto de inserção.
+
subscript
+
Ativa / desativa o subscrito para a seleção ou no ponto de inserção.
+
superscript
+
Ativa / desativa o superscript para a seleção ou no ponto de inserção.
+
underline
+
Ativa / desativa o underline para a seleção ou no ponto de inserção.
+
undo
+
Desfaz o último comando executado.
+
unlink
+
Remove o elemento âncora de um hiperlink selecionado.
+
useCSS {{Deprecated_inline}}
+
Alterna o uso de tags HTML ou CSS para a marcação gerada. Requer um booleano true / false como argumento.
+

+ NOTA: Este argumento é logicamente reverso (ou seja, use false para usar CSS, true para usar HTML) e não é suportado pelo Internet Explorer. Isso foi preterido em favor do styleWithCSS.
+
styleWithCSS
+
Substitui o comando useCSS. true modifica / gera atributos de style na marcação, false gera elementos de apresentação(html).
+
+
+ +

Exemplo

+ +

Um exemplo de como usar a funcionalidade no CodePen.

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
execCommand
+ +

Compatibilidade entre Browsers

+ + + +

{{Compat("api.Document.execCommand")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/document/fullscreen/index.html b/files/pt-br/web/api/document/fullscreen/index.html new file mode 100644 index 0000000000..6ad6fc604f --- /dev/null +++ b/files/pt-br/web/api/document/fullscreen/index.html @@ -0,0 +1,83 @@ +--- +title: Document.fullscreen +slug: Web/API/Document/fullscreen +tags: + - API + - Documento + - Javascript tela cheia + - Propriedade + - Referencia + - Somente Leitura + - Tela + - Tela Cheia + - display +translation_of: Web/API/Document/fullscreen +--- +
{{APIRef("Fullscreen API")}}{{Deprecated_Header}}
+ +

A propriedade de somente leitura da interface fullscreen retorna se o documento correspondente está mostrando conteúdo em modo de tela cheia (full-screen). 

+ +

Apesar dessa propriedade ser de somente leitura, ela não será executa se for modificada (mesmo em modo estrito); o setter não é um operador e não será modificado.

+ +
+

Nota: Desde que esta propriedade foi descontinuada, você pode determinar se o modo full-screen está ativo no documento checando se {{DOMxRef("Document.fullscreenElement")}} não é null.

+
+ +

Síntaxe

+ +
var isFullScreen = document.fullscreen;
+
+ +

Valor

+ +

Um valor booleano é true se o documento está mostrando um elemento no modo full-screen; se não, o valor é false.

+ +

Exemplo

+ +

Esta simples função retorna se o modo full-sreen está ativo, usando a obsoleta propriedade fullscreen.

+ +
function isDocumentInFullScreenMode() {
+  return document.fullscreen;
+}
+
+ +

Neste próximo exemplo, de outra maneira, usa a propriedade atual fullscreenElement para determinar a mesma coisa:

+ +
function isDocumentInFullScreenMode() {
+  return document.fullscreenElement !== null;
+}
+ +

Se fullscreenElement  não é null, retorna true, indicando se modo full-screen está sendo usado.

+ +

Específicações

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Fullscreen", "#dom-document-fullscreen", "Document.fullscreen")}}{{Spec2("Fullscreen")}}Definição inicial (como uma proprieda obsoleta).
+ +

Compatibilidade de navegadores

+ + + +

{{Compat("api.Document.fullscreen")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/document/getelementbyid/index.html b/files/pt-br/web/api/document/getelementbyid/index.html new file mode 100644 index 0000000000..c77a93fed9 --- /dev/null +++ b/files/pt-br/web/api/document/getelementbyid/index.html @@ -0,0 +1,133 @@ +--- +title: document.getElementById() +slug: Web/API/Document/getElementById +tags: + - API + - DOM + - Document + - Elements + - Method + - Reference + - Web + - getElementById + - id +translation_of: Web/API/Document/getElementById +--- +
{{ ApiRef("DOM") }}
+ +

Sumário

+ +

Retorna a referência do elemento através do seu ID.

+ +

Sintaxe

+ +
var elemento = document.getElementById(id);
+
+ +

onde

+ + + +

Exemplo

+ +
<!DOCTYPE html>
+<html>
+<head>
+  <title>Exemplo getElementById</title>
+  <script>
+  function mudarCor(novaCor) {
+    var elemento = document.getElementById("para1");
+    elemento.style.color = novaCor;
+  }
+  </script>
+</head>
+<body>
+  <p id="para1">Algum texto de exemplo</p>
+  <button onclick="mudarCor('blue');">Azul</button>
+  <button onclick="mudarCor('red');">Vermelho</button>
+</body>
+</html>
+
+ +

Notas

+ +

Os novatos devem notar que a caixa de 'Id' no nome deste método deve estar correta para o código da função - 'getElementByID não funciona, por mais natural que possa parecer.

+ +

Se não existe um elemento com o id fornecido, esta função retorna null. Note que o parâmetro ID diferência maiúsculas e minúsculas. Assim document.getElementById("Main") retornará null ao invés do elemento <div id="main">, devido a "M" e "m" serem diferentes para o objetivo deste método.

+ +

Elementos que não estão no documento não são procurados por getElementById. Quando criar um elemento e atribuir um ID ao mesmo, você deve inserir o elemento na árvore do documento com insertBefore ou método similar antes que você possa acessá-lo com getElementById:

+ +
var elemento = document.createElement("div");
+elemento.id = 'testqq';
+var el = document.getElementById('testqq'); // el será null!
+
+ +

Documentos não-HTML. A implementação do DOM deve ter informações que diz quais atributos são do tipo ID.  Atributos com o nome "id" não são do tipo ID a menos que assim sejam definidos nos documentos DTD. O atributo id é definido para ser um tipo ID em casos comuns de  XHTML, XUL, e outros. Implementações que não reconhecem se os atributos são do tipo ID, ou não são esperados retornam null.

+ +

Compatibilidade do Navegador

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
RecursoChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico1.0{{ CompatGeckoDesktop(1.0) }}5.57.01.0
+
+ +
+ + + + + + + + + + + + + + + + + + + +
RecursoAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte básico1.0{{ CompatGeckoMobile(1.0) }}6.06.01.0
+
+ +

Especificações

+ +

getElementById foi introduzido no DOM Level 1 para documentos HTML e movidos para todos documentos no DOM Level 2

+ + + +

Veja também

+ + diff --git a/files/pt-br/web/api/document/getelementsbyclassname/index.html b/files/pt-br/web/api/document/getelementsbyclassname/index.html new file mode 100644 index 0000000000..44fa28f840 --- /dev/null +++ b/files/pt-br/web/api/document/getelementsbyclassname/index.html @@ -0,0 +1,104 @@ +--- +title: Document.getElementsByClassName() +slug: Web/API/Document/getElementsByClassName +tags: + - API + - DOM + - Gecko + - HTML5 + - Métodos de Elementos DOM + - Referencia + - metodo +translation_of: Web/API/Document/getElementsByClassName +--- +

{{APIRef("DOM")}}

+ +

Retorna um vetor de objetos com todos os elementos filhos que possuem o nome da classe dada.  Quando invocado no objeto document, o documento é examinado por completo, incluindo o nó raiz. Você também pode invocar {{domxref("Element.getElementsByClassName", "getElementsByClassName()")}} em qualquer elemento; isso retornaria somente elementos que são descendentes do nó raiz especificado com o nome da classe.

+ +

Sintaxe

+ +
var elementos = document.getElementsByClassName(nomes); // ou:
+var elementos = rootElement.getElementsByClassName(nomes);
+ + + +

Exemplos

+ +

Retorna todos os elementos que possuem a classe 'teste'

+ +
document.getElementsByClassName('teste');
+ +

Retorna todos os elementos que possuem as classes 'vermelho' e 'teste'

+ +
document.getElementsByClassName('vermelho teste');
+ +

Retorna todos os elementos que possuem a classe 'teste' dentro do elemento que possui o ID 'principal'

+ +
document.getElementById('principal').getElementsByClassName('teste');
+ +

Nós podemos também usar os métodos do Array.prototype em qualquer dos elementos {{ domxref("HTMLCollection") }} passando o HTMLCollection como valor deste método. Aqui podemos encontrar todos os elementos do tipo div que possuem a classe 'teste':

+ +
var elementosTeste = document.getElementsByClassName('teste');
+var divsTeste = Array.prototype.filter.call(elementosTeste, function(elementoTeste) {
+    return elementoTeste.nodeName === 'DIV';
+});
+ +

Compatibilidade com navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticasChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{ CompatVersionUnknown() }}3.09.0{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticasAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

Especificação

+ + diff --git a/files/pt-br/web/api/document/getelementsbyname/index.html b/files/pt-br/web/api/document/getelementsbyname/index.html new file mode 100644 index 0000000000..8793259751 --- /dev/null +++ b/files/pt-br/web/api/document/getelementsbyname/index.html @@ -0,0 +1,90 @@ +--- +title: Document.getElementsByName() +slug: Web/API/Document/getElementsByName +translation_of: Web/API/Document/getElementsByName +--- +
{{APIRef("DOM")}}
+ +

O métodogetElementsByName() do objeto {{domxref("Document")}} retorna uma coleção de elementos {{domxref("NodeList")}} com um dado {{domxref("element.name","name")}} no documento.

+ +

Sintaxe

+ +
var elementos = document.getElementsByName(nome);
+
+ + + +

Exemplo

+ +
<!DOCTYPE html>
+<html lang="en">
+<title>Exemplo: usando document.getElementsByName</title>
+
+<input type="hidden" name="up">
+<input type="hidden" name="down">
+
+<script>
+  var up_nomes = document.getElementsByName("up");
+  console.log(up_nomes[0].tagName); // exibindo o campo "INPUT"
+</script>
+</html>
+
+ +

Notas

+ +

O atributo {{domxref("element.name","name")}} pode somente ser aplicado nos documentos (X)HTML.

+ +

A coleção retornada {{domxref("NodeList")}} contém todos os elementos com o respectivo nome, tal como {{htmlelement("meta")}}, {{htmlelement("object")}}, e até os elementos o qual não suporta o atributo nome para todos.

+ +
+

O método getElementsByName trabalha diferentemente em IE10 e anteriores. Além de que, getElementsByName() também retorna elementos que tem um atributo id com o valor especificado. Seja cuidadoso para não usar a mesma string como ambos nome e id.

+
+ +
+

O método getElementsByName trabalha diferentemente no IE. Portanto, getElementsByName() não retorna todos os elementos no qual não pode ter um atributo nome (tal como <span>).

+
+ +
+

Ambos IE e Edge retorna um {{domxref("HTMLCollection")}}, e não um {{domxref("NodeList")}}

+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + +
EpecificaçãoStatusComentário
{{SpecName('HTML WHATWG', '#dom-document-getelementsbyname', "Document.getElementsByName()")}}{{ Spec2('HTML WHATWG') }}
{{SpecName("DOM2 HTML", "html.html#ID-71555259", "Document.getElementsByName()")}}{{Spec2("DOM2 HTML")}}Definição Inicial
+ +

Compatibilidade com Nagevagores

+ + + +

{{Compat("api.Document.getElementsByName")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/document/getelementsbytagname/index.html b/files/pt-br/web/api/document/getelementsbytagname/index.html new file mode 100644 index 0000000000..3e786ed2f6 --- /dev/null +++ b/files/pt-br/web/api/document/getelementsbytagname/index.html @@ -0,0 +1,113 @@ +--- +title: Document.getElementsByTagName() +slug: Web/API/Document/getElementsByTagName +translation_of: Web/API/Document/getElementsByTagName +--- +
{{APIRef("DOM")}}
+ +

O método getElementsByTagName da interface Document retorna um HTMLCollection de elementos com o nome da tag fornecido. O documento completo é pesquisado, incluindo o nó raiz. A HTMLCollection retornada é ao vivo, o que significa que ela se atualiza automaticamente para permanecer em sincronia com a árvore DOM sem ter que chamar document.getElementsByTagName () novamente.

+ +

O método getElementsByTagName da {{domxref("Document")}} interface returns an {{domxref("HTMLCollection")}} of elements with the given tag name. The complete document is searched, including the root node. The returned HTMLCollection is live, meaning that it updates itself automatically to stay in sync with the DOM tree without having to call document.getElementsByTagName() again.

+ +

Syntax

+ +
var elements = document.getElementsByTagName(name);
+ + + +
The latest W3C specification says elements is an HTMLCollection; however, this method returns a {{domxref("NodeList")}} in WebKit browsers. See {{bug(14869)}} for details.
+ +

Example

+ +

In the following example, getElementsByTagName() starts from a particular parent element and searches top-down recursively through the DOM from that parent element, building a collection of all descendant elements which match the tag name parameter. This demonstrates both document.getElementsByTagName() and the functionally identical {{domxref("Element.getElementsByTagName()")}}, which starts the search at a specific element within the DOM tree.

+ +

Clicking the buttons uses getElementsByTagName() to count the descendant paragraph elements of a particular parent (either the document itself or one of two nested {{HTMLElement("div")}} elements).

+ +
<!DOCTYPE html>
+<html lang="en">
+<head>
+  <meta charset="UTF-8" />
+  <title>getElementsByTagName example</title>
+  <script>
+    function getAllParaElems() {
+      var allParas = document.getElementsByTagName('p');
+      var num = allParas.length;
+      alert('There are ' + num + ' paragraph in this document');
+    }
+
+    function div1ParaElems() {
+      var div1 = document.getElementById('div1');
+      var div1Paras = div1.getElementsByTagName('p');
+      var num = div1Paras.length;
+      alert('There are ' + num + ' paragraph in #div1');
+    }
+
+    function div2ParaElems() {
+      var div2 = document.getElementById('div2');
+      var div2Paras = div2.getElementsByTagName('p');
+      var num = div2Paras.length;
+      alert('There are ' + num + ' paragraph in #div2');
+    }
+  </script>
+</head>
+<body style="border: solid green 3px">
+  <p>Some outer text</p>
+  <p>Some outer text</p>
+
+  <div id="div1" style="border: solid blue 3px">
+    <p>Some div1 text</p>
+    <p>Some div1 text</p>
+    <p>Some div1 text</p>
+
+    <div id="div2" style="border: solid red 3px">
+      <p>Some div2 text</p>
+      <p>Some div2 text</p>
+    </div>
+  </div>
+
+  <p>Some outer text</p>
+  <p>Some outer text</p>
+
+  <button onclick="getAllParaElems();">
+    show all p elements in document</button><br />
+
+  <button onclick="div1ParaElems();">
+    show all p elements in div1 element</button><br />
+
+  <button onclick="div2ParaElems();">
+    show all p elements in div2 element</button>
+
+</body>
+</html>
+
+ +

Notes

+ +

When called on an HTML document, getElementsByTagName() lower-cases its argument before proceeding. This is undesirable when trying to match camelCase SVG elements in a subtree in an HTML document. {{Domxref("document.getElementsByTagNameNS()")}} is useful in that case. See also {{Bug(499656)}}.

+ +

document.getElementsByTagName() is similar to {{domxref("Element.getElementsByTagName()")}}, except that its search encompasses the whole document.

+ +

Specifications

+ + + +

Browser compatibility

+ + + +

{{Compat("api.Document.getElementsByTagName")}}

+ +

See also

+ + diff --git a/files/pt-br/web/api/document/getselection/index.html b/files/pt-br/web/api/document/getselection/index.html new file mode 100644 index 0000000000..9a2aab76d5 --- /dev/null +++ b/files/pt-br/web/api/document/getselection/index.html @@ -0,0 +1,8 @@ +--- +title: Document.getSelection() +slug: Web/API/Document/getSelection +translation_of: Web/API/DocumentOrShadowRoot/getSelection +--- +

{{APIRef("DOM")}}

+ +

Esse método funciona de forma idêntica ao método {{domxref("Window.getSelection()")}};  Ele retorna um objeto {{domxref("Selection")}} representando o texto atualmente selecionado no documento.

diff --git a/files/pt-br/web/api/document/hasfocus/index.html b/files/pt-br/web/api/document/hasfocus/index.html new file mode 100644 index 0000000000..0d238ec062 --- /dev/null +++ b/files/pt-br/web/api/document/hasfocus/index.html @@ -0,0 +1,146 @@ +--- +title: Document.hasFocus() +slug: Web/API/Document/hasFocus +tags: + - API + - Compatibilidade + - DOM + - Focus + - Referencia + - metodo +translation_of: Web/API/Document/hasFocus +--- +
{{APIRef}}
+ +
O método Document.hasFocus() retorna um valor {{jsxref("Boolean")}} que indica se o documento ou qualquer elemento dentro do documento está com o foco ativo. Este método pode ser usado para determinar se o elemento ativo em um documento tem foco.
+ +
+

Quando se está visualizando um documento, um elemento com focus é sempre o ativo no mesmo, mas um elemento ativo não necessariamente tem o foco. Por exemplo, um elemento ativo com uma janela (popup) que não é a principal não tem foco.

+
+ +

Sintaxe

+ +
focused = document.hasFocus();
+ +

Valor retornado

+ +

false se o elemento ativo no documento não tem foco; true se o elemento ativo no documento tem foco.

+ +

Exemplo

+ +
<!DOCTYPE html>
+<html lang="en">
+<head>
+<meta charset="UTF-8" />
+<title>TEST</title>
+<style>
+#message { font-weight: bold; }
+</style>
+<script>
+setInterval( checkPageFocus, 200 );
+
+function checkPageFocus() {
+  var info = document.getElementById("message");
+
+  if ( document.hasFocus() ) {
+    info.innerHTML = "O documento tem o foco.";
+  } else {
+    info.innerHTML = "O documento não tem o foco.";
+  }
+}
+
+function openWindow() {
+  window.open (
+    "http://developer.mozilla.org/",
+    "mozdev",
+    "width=640,
+    height=300,
+    left=150,
+    top=260"
+  );
+}
+</script>
+</head>
+<body>
+  <h1>Exemplo do JavaScript hasFocus</h1>
+  <div id="message">Esperando por ação do usuário</div>
+  <div><button onclick="openWindow()">Abre uma nova janela</button></div>
+</body>
+</html>
+ +

Especificação

+ + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', 'interaction.html#dom-document-hasfocus', 'Document.hasFocus()')}}{{Spec2('HTML WHATWG')}}Definição inicial
+ +

Compatibilidade de navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico30{{ CompatGeckoDesktop("1.9") }}6.0{{ CompatNo() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{ CompatUnknown() }}{{ CompatGeckoMobile("1.9") }}{{ CompatUnknown() }}{{ CompatNo() }}{{ CompatUnknown() }}
+
+ +

 

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/document/head/index.html b/files/pt-br/web/api/document/head/index.html new file mode 100644 index 0000000000..af0331459f --- /dev/null +++ b/files/pt-br/web/api/document/head/index.html @@ -0,0 +1,102 @@ +--- +title: Document.head +slug: Web/API/Document/head +translation_of: Web/API/Document/head +--- +

{{APIRef("DOM")}}

+ +

Retorna o elemento {{HTMLElement("head")}} do documento atual. Se existir mais de um elemento <head>, apenas o primeiro será devolvido.

+ +

Sintaxe

+ +
var objRef = document.head;
+
+ +

Exemplo

+ +
// No HTML: <head id="my-document-head">
+var aHead = document.head;
+
+alert(aHead.id); // "my-document-head";
+
+alert( document.head === document.querySelector("head") ); // true
+
+ +

Notas

+ +

document.head suporta apenas leitura. Qualquer tentativa de atribuir um valor a essa propriedade irá falhar silenciosamente ou irá, usando o modo ECMAScript Strict de um browser Gecko, disparar um TypeError.

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName("HTML5 W3C", "dom.html#dom-tree-accessors", "document.head")}}{{Spec2("HTML5 W3C")}}Definição inicial
+ +

Compatibilidade entre Browsers

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
RecursoChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico4.0{{CompatGeckoDesktop("2")}}9.011.05.0
+
+ +
+ + + + + + + + + + + + + + + + + + + +
RecursoAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatGeckoMobile("2")}}9.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

 

+ +

Veja Também

+ + diff --git a/files/pt-br/web/api/document/height/index.html b/files/pt-br/web/api/document/height/index.html new file mode 100644 index 0000000000..5dedba8f99 --- /dev/null +++ b/files/pt-br/web/api/document/height/index.html @@ -0,0 +1,44 @@ +--- +title: Document.height +slug: Web/API/Document/height +translation_of: Web/API/Document/height +--- +
{{APIRef("DOM")}} {{Obsolete_header}}
+ +
+

Nota: A partir do {{Gecko("6.0")}}, document.height  não é mais suportado. Em seu lugar use document.body.clientHeight. Veja {{domxref("element.clientHeight")}}.

+
+ +

Sumário

+ +

Retorna a altura do objeto {{domxref("document")}}. Em muitos casos, isto é igual à do elemento {{HTMLElement("body")}} do documento atual.

+ +

Sintaxe

+ +
height_value = document.height
+
+ +

Exemplo

+ +
// alert document height
+alert(document.height);
+
+ +

Alternativas

+ +
document.body.clientHeight
+document.documentElement.clientHeight
+document.documentElement.scrollHeight
+
+ +

Especificação

+ +

HTML5

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/document/images/index.html b/files/pt-br/web/api/document/images/index.html new file mode 100644 index 0000000000..f5021122a9 --- /dev/null +++ b/files/pt-br/web/api/document/images/index.html @@ -0,0 +1,38 @@ +--- +title: Document.images +slug: Web/API/Document/images +translation_of: Web/API/Document/images +--- +
+
{{ ApiRef("DOM") }}
+
+ +

Summary

+ +

document.images retorna uma coleção de imagens do documento HTML.

+ +

Sintaxe

+ +
var htmlCollection = document.images;
+ +

Exemplo

+ +
var ilist = document.images;
+
+for(var i = 0; i < ilist.length; i++) {
+    if(ilist[i].src == "banner.gif") {
+        // found the banner
+    }
+}
+ +

Notas

+ +

document.images.length – propriedade, retorna o número de imagens na página.

+ +

document.images é parte do DOM HTML, e só trabalho com documentos HTML.

+ +

Especificação

+ + diff --git a/files/pt-br/web/api/document/implementation/index.html b/files/pt-br/web/api/document/implementation/index.html new file mode 100644 index 0000000000..2f7b5ca992 --- /dev/null +++ b/files/pt-br/web/api/document/implementation/index.html @@ -0,0 +1,52 @@ +--- +title: Document.implementation +slug: Web/API/Document/implementation +tags: + - API + - DOM + - Propriedade + - Referencia +translation_of: Web/API/Document/implementation +--- +
{{ ApiRef("DOM") }}
+ +
 
+ +

Sumário

+ +

Retorna um objeto {{domxref("DOMImplementation")}} associado ao documento atual.

+ +

Sintaxe

+ +
DOMImpObj = document.implementation;
+
+ +

Exemplo

+ +
var modName = "HTML";
+var modVer = "2.0";
+var conformTest = document.implementation.hasFeature( modName, modVer );
+
+alert( "DOM " + modName + " " + modVer + " supported?: " + conformTest );
+
+// alerts with: "DOM HTML 2.0 supported?: true" if DOM Level 2 HTML module is supported.
+
+ +

Uma lista dos nomes de módulos (ex., Core, HTML, XML, etc) está disponível na DOM Level 2 Conformance Section

+ +

Notas

+ +

A Recomendação do W3C DOM Level 1 apenas especifica o método hasFeature, que é o único meio de verificar se o módulo DOM é suportado pelo navegador (veja exemplo acima e What does your user agent claim to support?). Quando disponível, outros métodos DOMImplementation proverão serviços para controlar coisas fora deste único documento. Por exemplo, a interface DOMImplementation inclui um método createDocumentType com o qual DTD's podem ser criados para um ou mais documentos gerenciados pela implementação.

+ +

Especificação

+ + + +

Notas específicas para o Gecko

+ + diff --git a/files/pt-br/web/api/document/importnode/index.html b/files/pt-br/web/api/document/importnode/index.html new file mode 100644 index 0000000000..831879f58f --- /dev/null +++ b/files/pt-br/web/api/document/importnode/index.html @@ -0,0 +1,84 @@ +--- +title: Document.importNode() +slug: Web/API/Document/importNode +translation_of: Web/API/Document/importNode +--- +

{{APIRef("DOM")}}

+ +

Cria uma cópia de um nó a partir de um documento externo para ser inserido no document atual.

+ +

Sintaxe

+ +
var node = document.importNode(externalNode, deep);
+
+ +
+
node
+
O novo nó que será importado no documento. A propriedade parentNode do novo nó é null, desde que ele não foi inserido na árvores do documento.
+
externalNode
+
O nó de outro documento para ser importado.
+
deep
+
Um boolean, indicando se os nós filhos, do nó a ser importado, devem ser importados também.
+
+ +
+

Note: In the DOM4 specification (as implemented in Gecko 13.0 {{geckoRelease(13)}}), deep is an optional argument. If omitted, the method acts as if the value of deep was true, defaulting to using deep cloning as the default behavior. To create a shallow clone, deep must be set to false.

+ +

This behavior has been changed in the latest spec, and if omitted, the method will act as if the value of deep was false. Though It's still optional, you should always provide the deep argument both for backward and forward compatibility. With Gecko 28.0 {{geckoRelease(28)}}, the console warned developers not to omit the argument. Starting with Gecko 29.0 {{geckoRelease(29)}}), a shallow clone is defaulted instead of a deep clone.

+
+ +

Exemplo

+ +
var iframe = document.getElementsByTagName("iframe")[0];
+var oldNode = iframe.contentWindow.document.getElementById("myNode");
+var newNode = document.importNode(oldNode, true);
+document.getElementById("container").appendChild(newNode);
+
+ +

Notas

+ +

O nó original não é removido do documento de origem. O nó importado é um clone do original.

+ +

 

+ +

Nodes from external documents should be cloned using document.importNode() (or adopted using document.adoptNode()) before they can be inserted into the current document. For more on the Node.ownerDocument issues, see the W3C DOM FAQ.

+ +

Firefox doesn't currently enforce this rule (it did for a while during the development of Firefox 3, but too many sites break when this rule is enforced). We encourage Web developers to fix their code to follow this rule for improved future compatibility.

+ +

 

+ +

Especificação

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("DOM WHATWG", "#dom-document-importnode", "document.importNode()")}}{{Spec2("DOM WHATWG")}} 
{{SpecName("DOM2 Core", "core.html#Core-Document-importNode", "document.importNode()")}}{{Spec2("DOM2 Core")}}Initial definition
+ +

Compatibilidade nos Browsers

+ +
+ + +

{{Compat("api.Document.importNode")}}

+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/document/index.html b/files/pt-br/web/api/document/index.html new file mode 100644 index 0000000000..1fc11a79ba --- /dev/null +++ b/files/pt-br/web/api/document/index.html @@ -0,0 +1,402 @@ +--- +title: Document +slug: Web/API/Document +translation_of: Web/API/Document +--- +
{{ ApiRef("DOM") }}
+ +
+ +

Para cada página carregada no browser, existe um objeto Document. A interface Document serve como um ponto de entrada para o conteúdo da Página ( a árvore DOM, incluindo elementos como {{HTMLElement("body")}} e {{HTMLElement("table")}}) e provê funcionalidades globais ao documento (como obter a URL da página e criar novos elementos no documento).

+ +

{{inheritanceDiagram}}

+ +

Um objeto document pode ser obtido por meio de várias APIs:

+ + + +

Dependendo do tipo do documento (e.g. HTML ou XML), diferentes APIs estarão disponívels no objeto Document.

+ +

Todo objeto Document implementa a interface Document (e consequentemente as interfaces {{domxref("Node")}} e {{domxref("EventTarget")}}). Portanto, as principais propriedades e métodos documentados nesta página estarão disponíveis para todos os tipos de documents.

+ + + +

No futuro, todas essas interfaces irão ser divididas na interface Document.

+ +

Propriedades

+ +
+

Nota: A interface Document também herda das interfaces {{domxref("Node")}} e {{domxref("EventTarget")}}.

+
+ +
+
{{domxref("Document.all")}} {{Deprecated_inline}} {{non-standard_inline}}
+
Da acesso a todos os elementos do documento.È uma interface legada não padrão, voce deve usar o método {{domxref("Document.getElementById()")}} como alternativa.
+
{{domxref("Document.async")}} {{Deprecated_inline}}
+
Usado como {{domxref("document.load")}} que indica uma requisição asyncroma.
+
{{domxref("Document.characterSet")}} {{experimental_inline}}
+
Retorna a codificação de caracteres que está sendo usado pelo documento.
+
{{domxref("Document.compatMode")}} {{experimental_inline}}
+
indica se o documento é renderizado no modo Quirks ou Strict.
+
{{domxref("Document.contentType")}} {{experimental_inline}}
+
Retorna o tipo de conteúdo do cabeçalho MIME do documento atual.
+
{{domxref("Document.doctype")}}
+
Retorna o nome do tipo de conteudo do documento HTML.
+
{{domxref("Document.documentElement")}}
+
Returns the Element that is a direct child of the document. For HTML documents, this is normally the HTML element.
+
{{domxref("Document.documentURI")}}
+
Returns the document URL.
+
{{domxref("Document.domConfig")}} {{Deprecated_inline}}
+
Should return a {{domxref("DOMConfiguration")}} object.
+
{{domxref("Document.implementation")}}
+
Returns the DOM implementation associated with the current document.
+
{{domxref("Document.inputEncoding")}} {{Deprecated_inline}}
+
Returns the encoding used when the document was parsed.
+
{{domxref("Document.lastStyleSheetSet")}}
+
Returns the name of the style sheet set that was last enabled. Has the value null until the style sheet is changed by setting the value of {{domxref("Document.selectedStyleSheetSet","selectedStyleSheetSet")}}.
+
{{domxref("Document.mozSyntheticDocument")}} {{non-standard_inline}} {{gecko_minversion_inline("8.0")}}
+
true if this document is synthetic, such as a standalone image, video, audio file, or the like.
+
{{domxref("Document.mozFullScreen")}} {{non-standard_inline}} {{gecko_minversion_inline("9.0")}}
+
true when the document is in {{domxref("Using_full-screen_mode","full-screen mode")}}.
+
{{domxref("Document.mozFullScreenElement")}} {{non-standard_inline}} {{gecko_minversion_inline("9.0")}}
+
The element that's currently in full screen mode for this document.
+
{{domxref("Document.mozFullScreenEnabled")}} {{non-standard_inline}} {{gecko_minversion_inline("9.0")}}
+
true if calling {{domxref("element.mozRequestFullscreen()")}} would succeed in the curent document.
+
{{domxref("Document.pointerLockElement")}} {{experimental_inline}}
+
Returns the element set as the target for mouse events while the pointer is locked. null if lock is pending, pointer is unlocked, or if the target is in another document.
+
{{domxref("Document.preferredStyleSheetSet")}}
+
Returns the preferred style sheet set as specified by the page author.
+
{{domxref("Document.selectedStyleSheetSet")}}
+
Returns which style sheet set is currently in use.
+
{{domxref("Document.styleSheets")}}
+
Returns a list of the style sheet objects on the current document.
+
{{domxref("Document.styleSheetSets")}}
+
Returns a list of the style sheet sets available on the document.
+
{{domxref("Document.xmlEncoding")}} {{Deprecated_inline}}
+
Returns the encoding as determined by the XML declaration.
+
{{domxref("Document.xmlStandalone")}} {{obsolete_inline("10.0")}}
+
Returns true if the XML declaration specifies the document to be standalone (e.g., An external part of the DTD affects the document's content), else false.
+
{{domxref("Document.xmlVersion")}} {{obsolete_inline("10.0")}}
+
Returns the version number as specified in the XML declaration or "1.0" if the declaration is absent.
+
+ +

The Document interface is extended with the {{domxref("ParentNode")}} interface:

+ +

{{page("/en-US/docs/Web/API/ParentNode","Properties")}}

+ +

Extension for HTML documents

+ +

The Document interface for HTML documents inherit from the {{domxref("HTMLDocument")}} interface or, since HTML5,  is extended for such documents:

+ +
+
{{domxref("Document.activeElement")}}
+
Returns the currently focused element.
+
{{domxref("Document.alinkColor")}} {{Deprecated_inline}}
+
Returns or sets the color of active links in the document body.
+
{{domxref("Document.anchors")}}
+
Returns a list of all of the anchors in the document.
+
{{domxref("Document.applets")}} {{Deprecated_inline}}
+
Returns an ordered list of the applets within a document.
+
{{domxref("Document.bgColor")}} {{Deprecated_inline}}
+
Gets/sets the background color of the current document.
+
{{domxref("Document.body")}}
+
Returns the {{HTMLElement("body")}} element of the current document.
+
{{domxref("Document.cookie")}}
+
Returns a semicolon-separated list of the cookies for that document or sets a single cookie.
+
{{domxref("Document.defaultView")}}
+
Returns a reference to the window object.
+
{{domxref("Document.designMode")}}
+
Gets/sets the ability to edit the whole document.
+
{{domxref("Document.dir")}}
+
Gets/sets directionality (rtl/ltr) of the document.
+
{{domxref("Document.domain")}}
+
Returns the domain of the current document.
+
{{domxref("Document.embeds")}}
+
Returns a list of the embedded {{HTMLElement('embed')}} elements within the current document.
+
{{domxref("Document.fgColor")}} {{Deprecated_inline}}
+
Gets/sets the foreground color, or text color, of the current document.
+
{{domxref("Document.forms")}}
+
Returns a list of the {{HTMLElement("form")}} elements within the current document.
+
{{domxref("Document.head")}}
+
Returns the {{HTMLElement("head")}} element of the current document.
+
{{domxref("Document.height")}} {{non-standard_inline}} {{obsolete_inline}}
+
Gets/sets the height of the current document.
+
{{domxref("Document.images")}}
+
Returns a list of the images in the current document.
+
{{domxref("Document.lastModified")}}
+
Returns the date on which the document was last modified.
+
{{domxref("Document.linkColor")}} {{Deprecated_inline}}
+
Gets/sets the color of hyperlinks in the document.
+
{{domxref("Document.links")}}
+
Returns a list of all the hyperlinks in the document.
+
{{domxref("Document.location")}}
+
Returns the URI of the current document.
+
{{domxref("Document.plugins")}}
+
Returns a list of the available plugins.
+
{{domxref("Document.readyState")}} {{gecko_minversion_inline("1.9.2")}}
+
Returns loading status of the document.
+
{{domxref("Document.referrer")}}
+
Returns the URI of the page that linked to this page.
+
{{domxref("Document.scripts")}}
+
Returns all the {{HTMLElement("script")}} elements on the document.
+
{{domxref("Document.title")}}
+
Returns the title of the current document.
+
{{domxref("Document.URL")}}
+
Returns a string containing the URL of the current document.
+
{{domxref("Document.vlinkColor")}} {{Deprecated_inline}}
+
Gets/sets the color of visited hyperlinks.
+
{{domxref("Document.width")}} {{non-standard_inline}} {{obsolete_inline}}
+
Returns the width of the current document.
+
+ +

Event handlers

+ +
+
{{domxref("Document.onpointerlockchange")}} {{experimental_inline}}
+
Returns the event handling code for the {{event("pointerlockchange")}} event.
+
{{domxref("Document.onpointerlockerror")}} {{experimental_inline}}
+
Returns the event handling code for the {{event("pointerlockerror")}} event.
+
{{domxref("Document.onreadystatechange")}} {{gecko_minversion_inline("1.9.2")}}
+
Returns the event handling code for the readystatechange event.
+
+ +

Methods

+ +
+

Note: The Document interface also inherits from the {{domxref("Node")}} and {{domxref("EventTarget")}} interfaces.

+
+ +
+
{{domxref("Document.adoptNode","Document.adoptNode(Node node)")}}
+
Adopt node from an external document.
+
{{domxref("Document.captureEvents","Document.captureEvents(String eventName)")}} {{Deprecated_inline}}
+
See {{domxref("window.captureEvents")}}.
+
{{domxref("Document.caretPositionFromPoint","Document.caretPositionFromPoint(Number x, Number y)")}}
+
Gets a {{domxref("CaretPosition")}} based on two coordinates.
+
{{domxref("Document.createAttribute","Document.createAttribute(String name)")}}
+
Creates a new {{domxref("Attr")}} object and returns it.
+
{{domxref("Document.createAttributeNS","Document.createAttributeNS(String namespace, String name)")}}
+
Creates a new attribute node in a given namespace and returns it.
+
{{domxref("Document.createCDATASection","Document.createCDATASection(String data)")}}
+
Creates a new CDATA node and returns it.
+
{{domxref("Document.createComment","Document.createComment(String comment)")}}
+
Creates a new comment node and returns it.
+
{{domxref("Document.createDocumentFragment()")}}
+
Creates a new document fragment.
+
{{domxref("Document.createElement","Document.createElement(String name)")}}
+
Creates a new element with the given tag name.
+
{{domxref("Document.createElementNS","Document.createElementNS(String namespace, String name)")}}
+
Creates a new element with the given tag name and namespace URI.
+
{{domxref("Document.createEntityReference","Document.createEntityReference(String name)")}} {{obsolete_inline}}
+
Creates a new entity reference object and returns it.
+
{{domxref("Document.createEvent","Document.createEvent(String interface)")}}
+
Creates an event object.
+
{{domxref("Document.createNodeIterator","Document.createNodeIterator(Node root[, Number whatToShow[, NodeFilter filter]])")}}
+
Creates a {{domxref("NodeIterator")}} object.
+
{{domxref("Document.createProcessingInstruction","Document.createProcessingInstruction(String target, String data)")}}
+
Creates a new {{domxref("ProcessingInstruction")}} object.
+
{{domxref("Document.createRange()")}}
+
Creates a {{domxref("Range")}} object.
+
{{domxref("Document.createTextNode","Document.createTextNode(String text)")}}
+
Creates a text node.
+
{{domxref("Document.createTreeWalker","Document.createTreeWalker(Node root[, Number whatToShow[, NodeFilter filter]])")}}
+
Creates a {{domxref("TreeWalker")}} object.
+
{{domxref("Document.elementFromPoint","Document.elementFromPoint(Number x, Number y)")}}
+
Returns the element visible at the specified coordinates.
+
{{domxref("Document.enableStyleSheetsForSet","Document.enableStyleSheetsForSet(String name)")}}
+
Enables the style sheets for the specified style sheet set.
+
{{domxref("Document.exitPointerLock()")}} {{experimental_inline}}
+
Release the pointer lock.
+
{{domxref("Document.getElementsByClassName","Document.getElementsByClassName(String className)")}}
+
Returns a list of elements with the given class name.
+
{{domxref("Document.getElementsByTagName","Document.getElementsByTagName(String tagName)")}}
+
Returns a list of elements with the given tag name.
+
{{domxref("Document.getElementsByTagNameNS","Document.getElementsByTagNameNS(String namespace, String tagName)")}}
+
Returns a list of elements with the given tag name and namespace.
+
{{domxref("Document.importNode","Document.importNode(Node node, Boolean deep)")}}
+
Returns a clone of a node from an external document.
+
{{domxref("document.mozSetImageElement")}} {{non-standard_inline}} {{gecko_minversion_inline("2.0")}}
+
Allows you to change the element being used as the background image for a specified element ID.
+
{{domxref("Document.normalizeDocument()")}} {{obsolete_inline}}
+
Replaces entities, normalizes text nodes, etc.
+
{{domxref("Document.releaseCapture()")}} {{non-standard_inline}} {{gecko_minversion_inline("2.0")}}
+
Releases the current mouse capture if it's on an element in this document.
+
{{domxref("Document.releaseEvents")}} {{non-standard_inline}} {{Deprecated_inline}}
+
See {{domxref("window.releaseEvents")}}.
+
{{domxref("document.routeEvent")}} {{non-standard_inline}} {{obsolete_inline(24)}}
+
See {{domxref("window.routeEvent")}}.
+
+ +

The Document interface is extended with the {{domxref("ParentNode")}} interface:

+ +
+
{{domxref("Document.getElementById","Document.getElementById(String id)")}}
+
Returns an object reference to the identified element.
+
{{domxref("Document.querySelector","Document.querySelector(String selector)")}} {{gecko_minversion_inline("1.9.1")}}
+
Returns the first Element node within the document, in document order, that matches the specified selectors.
+
{{domxref("Document.querySelectorAll","Document.querySelectorAll(String selector)")}} {{gecko_minversion_inline("1.9.1")}}
+
Returns a list of all the Element nodes within the document that match the specified selectors.
+
+ +

The Document interface is extended with the {{domxref("XPathEvaluator")}} interface:

+ +
+
{{domxref("Document.createExpression","Document.createExpression(String expression, XPathNSResolver resolver)")}}
+
Compiles an XPathExpression which can then be used for (repeated) evaluations.
+
{{domxref("Document.createNSResolver","Document.createNSResolver(Node resolver)")}}
+
Creates an {{domxref("XPathNSResolver")}} object.
+
{{domxref("Document.evaluate","Document.evaluate(String expression, Node contextNode, XPathNSResolver resolver, Number type, Object result)")}}
+
Evaluates an XPath expression.
+
+ +

Extension for HTML documents

+ +

The Document interface for HTML documents inherit from the {{domxref("HTMLDocument")}} interface or, since HTML5,  is extended for such documents:

+ +
+
{{domxref("Document.clear()")}} {{non-standard_inline}} {{Deprecated_inline}}
+
In majority of modern browsers, including recent versions of Firefox and Internet Explorer, this method does nothing.
+
{{domxref("Document.close()")}}
+
Closes a document stream for writing.
+
{{domxref("Document.execCommand","Document.execCommand(String command[, Boolean showUI[, String value]])")}}
+
On an editable document, executes a formating command.
+
{{domxref("Document.getElementsByName","Document.getElementsByName(String name)")}}
+
Returns a list of elements with the given name.
+
{{domxref("Document.getSelection()")}}
+
Returns a {{domxref("Selection")}} object related to text selected in the document.
+
{{domxref("Document.hasFocus()")}}
+
Returns true if the focus is currently located anywhere inside the specified document.
+
{{domxref("Document.open()")}}
+
Opens a document stream for writing.
+
{{domxref("Document.queryCommandEnabled","Document.queryCommandEnabled(String command)")}}
+
Returns true if the formating command can be executed on the current range.
+
{{domxref("Document.queryCommandIndeterm","Document.queryCommandIndeterm(String command)")}}
+
Returns true if the formating command is in an indeterminate state on the current range.
+
{{domxref("Document.queryCommandState","Document.queryCommandState(String command)")}}
+
Returns true if the formating command has been executed on the current range.
+
{{domxref("Document.queryCommandSupported","Document.queryCommandSupported(String command)")}}
+
Returns true if the formating command is supported on the current range.
+
{{domxref("Document.queryCommandValue","Document.queryCommandValue(String command)")}}
+
Returns the current value of the current range for a formatting command.
+
{{domxref("Document.registerElement","Document.registerElement(String tagname[, Object options])")}}
+
Registers a new custom element in the browser and returns a constructor for the new element.
+
{{domxref("Document.write","Document.write(String text)")}}
+
Writes text in a document.
+
{{domxref("Document.writeln","Document.writeln(String text)")}}
+
Writes a line of text in a document.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM1','#i-Document','Document')}}{{Spec2('DOM1')}}Initial definition for the interface
{{SpecName('DOM2 Core','#i-Document','Document')}}{{Spec2('DOM2 Core')}}Supersede DOM 1
{{SpecName('DOM3 Core','#i-Document','Document')}}{{Spec2('DOM3 Core')}}Supersede DOM 2
{{SpecName('DOM WHATWG','#interface-document','Document')}}{{Spec2('DOM WHATWG')}}Intend to supersede DOM 3
{{SpecName('HTML WHATWG','dom.html#the-document-object','Document')}}{{Spec2('HTML WHATWG')}}Turn the {{domxref("HTMLDocument")}} interface into a Document extension.
{{SpecName('DOM3 XPath','xpath.html#XPathEvaluator','XPathEvaluator')}}{{Spec2('DOM3 XPath')}}Define the {{domxref("XPathEvaluator")}} interface which extend Document.
{{SpecName('HTML Editing','#dom-document-getselection','Document')}}{{Spec2('HTML Editing')}}Extend the Document interface
{{SpecName('CSSOM View','#extensions-to-the-document-interface','Document')}}{{Spec2('CSSOM View')}}Extend the Document interface
{{SpecName('CSSOM','#extensions-to-the-document-interface','Document')}}{{Spec2('CSSOM')}}Extend the Document interface
{{SpecName('Pointer Lock','#extensions-to-the-document-interface','Document')}}{{Spec2('Pointer Lock')}}Extend the Document interface
+ +

Browser compatibility

+ +

Firefox notes

+ +

Mozilla defines a set of non-standard properties made only for XUL content:

+ +
+
{{domxref("document.currentScript")}} {{gecko_minversion_inline("2.0")}}
+
Returns the {{HTMLElement("script")}} element that is currently executing.
+
{{domxref("document.documentURIObject")}} {{gecko_minversion_inline("1.9")}}
+
(Mozilla add-ons only!) Returns the {{Interface("nsIURI")}} object representing the URI of the document. This property only has special meaning in privileged JavaScript code (with UniversalXPConnect privileges).
+
{{domxref("document.popupNode")}}
+
Returns the node upon which a popup was invoked.
+
{{domxref("document.tooltipNode")}}
+
Returns the node which is the target of the current tooltip.
+
+ +

Mozilla also define some non-standard methods:

+ +
+
{{domxref("Document.execCommandShowHelp")}} {{obsolete_inline("14.0")}}
+
This method never did anything and always threw an exception, so it was removed in Gecko 14.0 {{geckoRelease("14.0")}}.
+
{{domxref("Document.getBoxObjectFor")}} {{obsolete_inline}}
+
Use the {{domxref("Element.getBoundingClientRect()")}} method instead.
+
{{domxref("Document.loadOverlay")}} {{Fx_minversion_inline("1.5")}}
+
Loads a XUL overlay dynamically. This only works in XUL documents.
+
{{domxref("document.queryCommandText")}} {{obsolete_inline("14.0")}}
+
This method never did anything but throw an exception, and was removed in Gecko 14.0 {{geckoRelease("14.0")}}.
+
+ +

Internet Explorer notes

+ +

Microsoft defines some non-standard properties:

+ +
+
{{domxref("document.fileSize")}}* {{non-standard_inline}} {{obsolete_inline}}
+
Returns size in bytes of the document. Starting with Internet Explorer 11, that property is no longer supported. See MSDN.
+
Internet Explorer does not support all methods from the Node interface in the Document interface:
+
+ +
+
{{domxref("document.contains")}}
+
As a work-around, document.body.contains() can be used.
+
diff --git a/files/pt-br/web/api/document/keydown_event/index.html b/files/pt-br/web/api/document/keydown_event/index.html new file mode 100644 index 0000000000..4abd69eab7 --- /dev/null +++ b/files/pt-br/web/api/document/keydown_event/index.html @@ -0,0 +1,178 @@ +--- +title: keydown +slug: Web/API/Document/keydown_event +translation_of: Web/API/Document/keydown_event +--- +

O evento keydown é disparado quando uma tecla é pressionada. Diferente do evento keypress, o keydown é disparado para teclas que produzem e que não produzem um caractere.

+ +

Informações gerais

+ +
+
Especificação
+
DOM L3
+
Interface
+
KeyboardEvent
+
Burbulha
+
Sim
+
Cancelável
+
Sim
+
Alvo
+
Document, Element
+
Ação Padrão
+
Variações: evento keypress; carrega sistema de composição de texto; eventos blur e focus; evento DOMActivate; outro evento
+
+ +

Propriedades

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropriedadeTipoDescrição
target {{readonlyInline}}EventTargetO alvo do evento (o alvo de nível mais alto na árvore DOM).
type {{readonlyInline}}DOMStringO tipo do evento.
bubbles {{readonlyInline}}BooleanSe o evento normalmente burbulha ou não
cancelable {{readonlyInline}}BooleanSe o evento é cancelável ou não
view {{readonlyInline}}WindowProxydocument.defaultView (window do documento)
detail {{readonlyInline}}long (float)0.
target {{readonlyInline}}EventTarget (elemento DOM)Elemento focado processando o evento, elemento raiz se nenhum elemento input adequado está focado.
char {{readonlyInline}}DOMString (string)O caractere correspondente à tecla. Se a tecla corresponde a um caractere imprimível, este valor é uma string Unicode não vazia, contendo o caractere. Se a tecla não tem uma representação imprimível, o valor é uma string vazia. Veja key names and char values para detalhes. +
Nota: Se a tecla for usada como uma macro que insere múltiplos caracteres, o valor deste atributo é toda a string, não apenas o primeiro caractere.
+
key {{readonlyInline}}DOMString (string)O valor da tecla pressionada. Se a tecla tem uma representação imprimível, o valor deste atributo é o mesmo do atributo char. Caso contrário, é uma das strings key especificadas em Key Values. Se a tecla não pode ser identificada, o valor do atributo é a string "Unidentified". Veja key names and char values para detalhes. Somente Leitura.
code {{readonlyInline}}DOMString (string)Mantém uma string que identifica a tecla física sendo pressionada. O valor não é afetado pelo layout atual do teclado ou estado de modificador, portando uma tecla particular sempre retornará o mesmo valor. 
charCode {{readonlyInline}}Unsigned long (int)O número de referência Unicode da tecla; este atributo é usado somente pelo evento keypress. Para teclas cujo atributo char contém múltiplos caracteres, este é o valor Unicode do primeiro caractere daquele atributo. +
Aviso: Este atributo está obsoleto; você deve usar char no lugar, se disponível.
+
keyCode {{readonlyInline}}Unsigned long (int)Um código numérico, dependente do sistema e da implementação, identificando o valor não modificado da tecla pressionada. Este é usualmente o código decimal ASCII ({{ RFC(20) }}) ou código Windows 1252 correspondente à tecla; veja {{ anch("Virtual key codes") }} para uma lista de valores comuns. Se a tecla não pode ser identificada, este valor é 0. +
Aviso: Este atributo está obsoleto; você deve usar key no lugar, se disponível.
+
which {{readonlyInline}}Unsigned long (int)Um código numérico, dependente do sistema e da implementação, identificando o valor não modificado da tecla pressionada; este é usualmente o mesmo que keyCode. +
Aviso: Este atributo está obsoleto; você deve usar key no lugar, se disponível.
+
location {{readonlyInline}}long (float)A localização da tecla no dispositivo.
repeat {{readonlyInline}}booleantrue se a tecla foi pressionada tempo suficiente para disparar repetição de tecla, false caso contrário.
locale {{readonlyInline}}stringO código do idioma para o evento, se disponível; uma string vazia caso contrário.
ctrlKey {{readonlyInline}}booleantrue se a tecla control estava pressionada quando o evento foi disparado. false caso contrário.
shiftKey {{readonlyInline}}booleantrue se a tecla shift estava pressionada quando o evento foi disparado. false caso contrário.
altKey {{readonlyInline}}booleantrue se a tecla alt estava pressionada quando o evento foi disparado. false caso contrário.
metaKey {{readonlyInline}}booleantrue se a tecla meta estava pressionada quando o evento foi disparado. false caso contrário.
+ +

preventDefault() do evento keydown

+ +

Iniciando com o Gecko 25, uma chamada para o método preventDefault() do evento keydown evita dispachar o evento keypress seguinte. Este é um comportamento válido para a especificação D3E e os principais navegadores web se comportam desta forma. Por outro lado, o Gecko 24 e anteriores dispachavam o evento keypress mesmo que o método preventDefault() do evento keydown anterior fosse chamado, embora o atributo  defaultPrevented do evento keypress fosse true neste caso.

+ +

Eventos Relacionados

+ + + +

Exemplo

+ +
<!DOCTYPE html>
+<html>
+<head>
+<script>
+
+'use strict';
+
+document.addEventListener('keydown', (event) => {
+  const keyName = event.key;
+  alert('keydown event\n\n' + 'key: ' + keyName);
+});
+
+</script>
+</head>
+<body>
+</body>
+</html>
diff --git a/files/pt-br/web/api/document/keypress_event/index.html b/files/pt-br/web/api/document/keypress_event/index.html new file mode 100644 index 0000000000..e22242028b --- /dev/null +++ b/files/pt-br/web/api/document/keypress_event/index.html @@ -0,0 +1,170 @@ +--- +title: keypress +slug: Web/API/Document/keypress_event +translation_of: Web/API/Document/keypress_event +--- +
{{APIRef}}
+ +

O evento keypress é disparado quando uma tecla que produz um valor do tipo caractere é pressionada. Exemplos de chaves que produzem um valor de caractere são chaves alfabéticas, numéricas e de pontuação. Exemplos de chaves que não produzem um valor de caractere são as teclas modificadoras, como Alt, Shift, Ctrl, ou Meta.

+ +

Informações gerais

+ +
+
Especificação
+
DOM L3 {{deprecated_inline ()}}
+
Interface
+
KeyboardEvent
+
Bolhas
+
sim
+
Cancelável
+
sim
+
Alvo
+
Documento, Elemento
+
Ação padrão
+
Varia: keypressevento; lançar sistema de composição de texto; blure focuseventos; DOMActivateevento; outro evento
+
+ +

Propriedades

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropriedadeTipoDescrição
target {{readonlyInline}}EventTargetO destino do evento (o destino mais alto na árvore do DOM).
type {{readonlyInline}}DOMStringO tipo de evento.
bubbles {{readonlyInline}}boleanoSe o evento normalmente borbulha ou não
cancelable {{readonlyInline}}boleanoSe o evento é cancelável ou não
view {{readonlyInline}}WindowProxydocument.defaultView( windowdo documento)
detail {{readonlyInline}}long( float)0
target {{readonlyInline}}EventTarget (elemento DOM)Elemento focalizado processando o evento chave, elemento raiz se nenhum elemento de entrada adequado estiver focalizado.
char {{readonlyInline}}DOMString (string)O valor do caractere da chave. Se a chave corresponder a um caractere imprimível, esse valor será uma string Unicode não vazia contendo esse caractere. Se a chave não tiver uma representação imprimível, esta é uma string vazia. Veja nomes de chaves e valores de caracteres para os detalhes. +
Nota: Se a chave for usada como uma macro que insere vários caracteres, o valor desse atributo é a cadeia inteira, não apenas o primeiro caractere.
+
key {{readonlyInline}}DOMString (string) +

O valor-chave da chave representada pelo evento. Se o valor tiver uma representação impressa, o valor desse atributo será o mesmo da charpropriedade. Caso contrário, é uma das cadeias de valores de chave especificadas nos valores de chave . Se a chave não puder ser identificada, seu valor será a string "Unidentified". Veja os nomes das chaves e os valores de caracteres para mais detalhes. Somente leitura.

+
code {{readonlyInline}}DOMString (string)Contém uma string que identifica a tecla física sendo pressionada. O valor não é afetado pelo layout do teclado atual ou pelo estado do modificador, portanto, uma chave específica sempre retornará o mesmo valor.
charCode {{readonlyInline}}Longo não assinado (int)O número de referência Unicode da chave; esse atributo é usado apenas pelo keypressevento. Para chaves cujo charatributo contém vários caracteres, esse é o valor Unicode do primeiro caractere nesse atributo. +
Aviso: este atributo está obsoleto; você deve usar em charvez disso, se disponível.
+
keyCode {{readonlyInline}}Longo não assinado (int)Um código numérico dependente do sistema e da implementação que identifica o valor não modificado da tecla pressionada. Este é geralmente o código ASCII decimal ({{RFC (20)}}) ou Windows 1252 correspondente à chave; veja {{anch ("Códigos de teclas virtuais")}} para uma lista de valores comuns. Se a chave não puder ser identificada, esse valor será 0. +
Aviso: este atributo está obsoleto; você deve usar em keyvez disso, se disponível.
+
which {{readonlyInline}}Longo não assinado (int)Um código numérico dependente do sistema e da implementação identificando o valor não modificado da tecla pressionada; isso geralmente é o mesmo que keyCode. +
Aviso: este atributo está obsoleto; você deve usar em keyvez disso, se disponível.
+
location {{readonlyInline}}longo (flutuar)A localização da chave no dispositivo.
repeat {{readonlyInline}}boleanotruese uma tecla foi pressionada o tempo suficiente para disparar a repetição da tecla, caso contrário false.
locale {{readonlyInline}}cordaO código do idioma para o evento principal, se disponível; caso contrário, a cadeia vazia.
ctrlKey {{readonlyInline}}boleanotruese a chave de controle estava inativa quando o evento foi disparado. falsede outra forma.
shiftKey {{readonlyInline}}boleanotruese a tecla shift estava inativa quando o evento foi disparado. falsede outra forma.
altKey {{readonlyInline}}boleanotruese a tecla ALT estava desativada quando o evento foi disparado. falsede outra forma.
metaKey {{readonlyInline}}boleanotruese a meta key estava desativada quando o evento foi disparado. falsede outra forma.
+ +

Exemplo

+ +
document.addEventListener ('keypress', (event) => {
+  const keyName = event.key;
+  alert ('keypress event \ n \ n' + 'chave:' + nome da chave);
+});
+
+ +

Compatibilidade do navegador

+ +

O Chrome não dispara o keypressevento para atalhos de teclado conhecidos ( referência ). Quais atalhos de teclado são conhecidos depende do sistema do usuário. Use o keydownevento para implementar atalhos de teclado.

+ +

Eventos Relacionados

+ + diff --git a/files/pt-br/web/api/document/keyup_event/index.html b/files/pt-br/web/api/document/keyup_event/index.html new file mode 100644 index 0000000000..6423993b63 --- /dev/null +++ b/files/pt-br/web/api/document/keyup_event/index.html @@ -0,0 +1,151 @@ +--- +title: keyup +slug: Web/API/Document/keyup_event +tags: + - Evento de teclado +translation_of: Web/API/Document/keyup_event +--- +

O evento keyup é acionado quando uma tecla é liberada.

+ +

Informações gerais

+ +
+
Especificação
+
DOM L3
+
Interface
+
KeyboardEvent
+
Método Bolha
+
Sim
+
Cancelável
+
Sim
+
Alvo
+
Documento, Elemento
+
Ação Padrão
+
Nenhuma
+
+ +

Propriedades

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
target {{readonlyInline}}EventTargetThe event target (the topmost target in the DOM tree).
type {{readonlyInline}}DOMStringThe type of event.
bubbles {{readonlyInline}}BooleanWhether the event normally bubbles or not
cancelable {{readonlyInline}}BooleanWhether the event is cancellable or not?
view {{readonlyInline}}WindowProxydocument.defaultView (window of the document)
detail {{readonlyInline}}long (float)0.
target {{readonlyInline}}EventTarget (DOM element)Focused element processing the key event, root element if no suitable input element focused.
char {{readonlyInline}}DOMString (string)The character value of the key. If the key corresponds to a printable character, this value is a non-empty Unicode string containing that character. If the key doesn't have a printable representation, this is an empty string. See key names and char values for the detail. +
Note: If the key is used as a macro that inserts multiple characters, this attribute's value is the entire string, not just the first character.
+
key {{readonlyInline}}DOMString (string)The key value of the key represented by the event. If the value has a printed representation, this attribute's value is the same as the char attribute. Otherwise, it's one of the key value strings specified in {{ anch("Key values") }}. If the key can't be identified, this is the string "Unidentified". See key names and char values for the detail. Read Only.
charCode {{readonlyInline}}Unsigned long (int)The Unicode reference number of the key; this attribute is used only by the keypress event. For keys whose char attribute contains multiple characters, this is the Unicode value of the first character in that attribute. +
Warning: This attribute is deprecated; you should use char instead, if available.
+
keyCode {{readonlyInline}}Unsigned long (int)A system and implementation dependent numerical code identifying the unmodified value of the pressed key. This is usually the decimal ASCII ({{ RFC(20) }}) or Windows 1252 code corresponding to the key; see {{ anch("Virtual key codes") }} for a list of common values. If the key can't be identified, this value is 0. +
Warning: This attribute is deprecated; you should use key instead, if available.
+
which {{readonlyInline}}Unsigned long (int)A system and implementation dependent numeric code identifying the unmodified value of the pressed key; this is usually the same as keyCode. +
Warning: This attribute is deprecated; you should use key instead, if available.
+
location {{readonlyInline}}long (float)The location of the key on the device.
repeat {{readonlyInline}}booleantrue if a key has been depressed long enough to trigger key repetition, otherwise false.
locale {{readonlyInline}}stringThe language code for the key event, if available; otherwise, the empty string.
ctrlKey {{readonlyInline}}booleantrue if the control key was down when the event was fired. false otherwise.
shiftKey {{readonlyInline}}booleantrue if the shift key was down when the event was fired. false otherwise.
altKey {{readonlyInline}}booleantrue if the alt key was down when the event was fired. false otherwise.
metaKey {{readonlyInline}}booleantrue if the meta key was down when the event was fired. false otherwise.
+ +

Eventos Relacionados

+ + diff --git a/files/pt-br/web/api/document/location/index.html b/files/pt-br/web/api/document/location/index.html new file mode 100644 index 0000000000..ebf1f2aa27 --- /dev/null +++ b/files/pt-br/web/api/document/location/index.html @@ -0,0 +1,108 @@ +--- +title: Document.location +slug: Web/API/Document/location +translation_of: Web/API/Document/location +--- +

{{APIRef("DOM")}}

+ +

A propriedade, de apenas leitura, Document.location retorna um objeto {{domxref("Location")}}, que contém informações sobre a URL do documento e provém métodos para mudar a URL e carregar outra URL.

+ +

Embora Document.location seja um objeto Location de apenas leitura,  você pode atribuir um {{domxref("DOMString")}} para ele. Isso significa que você pode trabalhar com document.location, na maioria dos casos, como se fosse uma string: document.location = 'http://www.example.com' é um sinônimo de document.location.href = 'http://www.example.com'.

+ +

Para recuperar somente a URL como uma string, a propriedade de apenas leitura {{domxref("document.URL")}} pode ser utilizada.

+ +

Se o documento atual não estiver no contexto de navegação, o valor retornado será null.

+ +

Sintaxe

+ +
locationObj = document.location
+document.location = 'http://www.mozilla.org' // Equivalente a document.location.href = 'http://www.mozilla.org'
+
+ +

Exemplo

+ +
dump(document.location);
+// Imprime uma string como
+// "http://www.example.com/juicybits.html" to the console
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG', "history.html#the-location-interface", "Document.location")}}{{Spec2('HTML WHATWG')}}Nenhuma mudança de {{SpecName("HTML5 W3C")}}.
{{SpecName('HTML5 W3C', "browsers.html#the-location-interface", "Document.location")}}{{Spec2('HTML5 W3C')}}Definição inicial.
+ +

Compatibilidade de navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticasChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticasAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Veja também

+ + + +

 

diff --git a/files/pt-br/web/api/document/origin/index.html b/files/pt-br/web/api/document/origin/index.html new file mode 100644 index 0000000000..b31decf05f --- /dev/null +++ b/files/pt-br/web/api/document/origin/index.html @@ -0,0 +1,60 @@ +--- +title: Document.origin +slug: Web/API/Document/origin +translation_of: Web/API/Document/origin +--- +
{{APIRef("DOM")}}{{SeeCompatTable}}
+ +

A propriedade read-only Document.origin retorna a origem do documento. Na maioria dos casos, essa propriedade é equivalente a document.defaultView.location.origin.

+ +

Sintaxe

+ +
var origin = document.origin;
+ +

Exemplos

+ +
var origin = document.origin;
+// Nesta página, retorna:'https://developer.mozilla.org'
+
+var origin = document.origin;
+// Em "about:blank", retorna:'null'
+
+var origin = document.origin;
+// Em "data:text/html,<b>foo</b>", retorna:'null'
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('DOM WHATWG', '#dom-document-origin', 'Document.origin')}}{{Spec2('DOM WHATWG')}}Definição inicial.
{{SpecName('HTML WHATWG', '#concept-origin', 'origin for various objects (including Document objects)')}}{{Spec2('HTML WHATWG')}}Definição inicial.
+ +

Compatibilidade entre navegadores

+ + + +
{{Compat("api.Document.origin")}}
+ +

Veja também 

+ + diff --git a/files/pt-br/web/api/document/queryselector/index.html b/files/pt-br/web/api/document/queryselector/index.html new file mode 100644 index 0000000000..4489a2e823 --- /dev/null +++ b/files/pt-br/web/api/document/queryselector/index.html @@ -0,0 +1,107 @@ +--- +title: Document.querySelector() +slug: Web/API/Document/querySelector +translation_of: Web/API/Document/querySelector +--- +
+
{{ ApiRef("DOM") }}
+
+ +

Sumário

+ +

Retorna o primeiro elemento dentro do documento (usando ordenação em profundidade, pré-ordenada e transversal dos nós do documento) que corresponde ao grupo especificado de seletores.

+ +

Sintaxe

+ +
element = document.querySelector(selectors);
+ +

Onde:

+ + + +

Exemplo

+ +

Neste exemplo, o primeiro elemento no documento com a classe "myclass" é retornado:

+ +
var el = document.querySelector(".myclass");
+
+ +

Notas

+ +

Retorna null se nenhum resultado for encontrado; caso contrário, retorna o primeiro elemento correspondente.

+ +

Se o seletor utilizado for um ID e este ID foi erroneamente utilizado várias vezes no documento, ele retorna somente o primeiro elemento correspondente.

+ +

Gera uma exceção SYNTAX_ERR se o grupo de seletores utilizado for inválido.

+ +

querySelector() foi introduzido com a API de seletores.

+ +

Compatibilidade dos navegadores

+ +

{{CompatibilityTable()}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support13.5 (1.9.1)
+ {{bug(416317)}}
8103.2 (525.3)
+ {{Webkitbug("16587")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support2.1yes910.03.2
+
+ +

Especificação

+ + + +

Veja também:

+ + diff --git a/files/pt-br/web/api/document/queryselectorall/index.html b/files/pt-br/web/api/document/queryselectorall/index.html new file mode 100644 index 0000000000..0a05a06180 --- /dev/null +++ b/files/pt-br/web/api/document/queryselectorall/index.html @@ -0,0 +1,110 @@ +--- +title: Document.querySelectorAll() +slug: Web/API/Document/querySelectorAll +tags: + - CSS + - JavaScript + - querySelector +translation_of: Web/API/Document/querySelectorAll +--- +

{{ ApiRef("DOM") }}

+ +

Introdução

+ +

Retorna uma lista de elementos presentes no documento (usando ordenação em profundidade, pré-ordenada e transversal dos nós do documento) que coincidam com o grupo de seletores especificado. O objeto retornado é uma {{ domxref("NodeList") }}.

+ +

Sintaxe

+ +
elementList = document.querySelectorAll(selectors);
+
+ +

onde

+ + + +

A NodeList retornada irá conter todos os elementos do documento que coincidam com os seletores especificados. Se a string selectors conter um CSS {{ cssxref("PseudoElements") }}, o retorno será uma NodeList vazia.

+ +

Exemplo

+ +

Esse exemplo retorna uma lista de todos os elementos div presentes no document que contenham as classes "note" ou "alert":

+ +
var matches = document.querySelectorAll("div.note, div.alert");
+
+ +

Notas

+ +

Retorna uma {{ jsxref("NodeList") }} não-viva (alterações no DOM não refletem na lista) de todos os elementos que coincidam com os seletores informados.

+ +

Lança uma exceção SYNTAX_ERR se o grupo especificado de seletores for inválido.

+ +

querySelectorAll() foi introduzida na WebApps API.

+ +

Navegadores baseados em WebKit têm um bug: quando a string seletores contém um pseudo-elemento CSS, a {{ jsxref("NodeList") }} retornada não esta vazia, neste caso ela contém o elemento {{ HTMLElement("html") }}.

+ +

Compatibilidade nos navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
PossuiChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico13.5 (1.9.1)8103.2 (525.3)
+
+ +
+ + + + + + + + + + + + + + + + + + + +
PossuiAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico2.1sim910.03.2
+
+ +

Especificação

+ + + +

Veja também

+ + diff --git a/files/pt-br/web/api/document/readystate/index.html b/files/pt-br/web/api/document/readystate/index.html new file mode 100644 index 0000000000..d5d2cea5cd --- /dev/null +++ b/files/pt-br/web/api/document/readystate/index.html @@ -0,0 +1,102 @@ +--- +title: Document.readyState +slug: Web/API/Document/readyState +tags: + - API + - HTML DOM + - Propriedade + - Referencia + - eventos +translation_of: Web/API/Document/readyState +--- +
{{APIRef("DOM")}} {{ gecko_minversion_header("1.9.2") }}
+ +

Sumário

+ +

Retorna "loading" enquanto {{ domxref("document") }} está carregando, "interactive" quando foi carregado porém seus sub-recursos (como imagens, por exemplo) ainda não, e "complete" quando foi totalmente carregado.

+ +
O evento readystatechange é acionado no objeto {{ domxref("document") }} quando esse valor é alterado.
+ +

Sintaxe

+ +
var string = document.readyState;
+
+ + + +

Valores

+ +

readyState de um documento pode ser um dos seguintes:

+ +
+
loading
+
O {{domxref("document")}} ainda está carregando.
+
interactive
+
O documento terminou de ser carregado e o documento foi analisado, mas sub-recursos, como imagens, folhas de estilo e quadros, ainda estão sendo carregados.
+
complete
+
O documento e todos os sub-recursos terminaram de carregar. O estado indica que o {{event("load")}} evento está prestes a disparar.
+
+ + + +

Exemplos

+ +

Diferentes estados de readyState

+ +
switch (document.readyState) {
+  case "loading":
+    // O documento esta carregando
+    break;
+  case "interactive":
+    // O documento acabou de carregar. Nós podemos acessar os elementos do DOM.
+    // mas sub-recursos, como imagens, folhas de estilo e quadros, ainda estão sendo carregados.
+    var span = document.createElement("span");
+    span.textContent = "A <span> element.";
+    document.body.appendChild(span);
+    break;
+  case "complete":
+    // A pagina carregou por completo.
+    console.log("The first CSS rule is: " + document.styleSheets[0].cssRules[0].cssText);
+    break;
+}
+ +

readystatechange como uma alternativa para DOMContentLoaded evento

+ +
// alternativa para DOMContentLoaded evento
+document.onreadystatechange = function () {
+  if (document.readyState === 'interactive') {
+    initApplication();
+  }
+}
+ +

readystatechange como uma alternativa para load evento

+ +
// ternativa para load evento
+document.onreadystatechange = function () {
+  if (document.readyState === 'complete') {
+    initApplication();
+  }
+}
+ +

readystatechange como ouvinte de evento para inserir ou modificar o DOM antes de DOMContentLoaded

+ +
document.addEventListener('readystatechange', event => {
+  if (event.target.readyState === 'interactive') {
+    initLoader();
+  }
+  else if (event.target.readyState === 'complete') {
+    initApp();
+  }
+});
+ +

Especificação

+ + + +

Veja também

+ + diff --git a/files/pt-br/web/api/document/referrer/index.html b/files/pt-br/web/api/document/referrer/index.html new file mode 100644 index 0000000000..cbf8da950d --- /dev/null +++ b/files/pt-br/web/api/document/referrer/index.html @@ -0,0 +1,33 @@ +--- +title: Document.referrer +slug: Web/API/Document/referrer +tags: + - API + - Anterior + - HTML DOM + - NeedsCompatTable + - NeedsMarkupWork + - NeedsSpecTable + - Propriedade + - Página(2) + - Referência(2) +translation_of: Web/API/Document/referrer +--- +
{{APIRef("DOM")}}
+ +

Retorna o URI da página que continha o link para a página atual.

+ +

Sintaxe

+ +
string = document.referrer;
+
+ +

Notas

+ +

O valor retornado será uma string vazia se o usuário tiver chegado na página diretamente (digitando o endereço no navegador ou como um item "Favorito"). Como essa propriedade retorna apenas uma string, ela não dá acesso DOM à página que fez a referência.

+ +

Especificação

+ + diff --git a/files/pt-br/web/api/document/scripts/index.html b/files/pt-br/web/api/document/scripts/index.html new file mode 100644 index 0000000000..f896f837e8 --- /dev/null +++ b/files/pt-br/web/api/document/scripts/index.html @@ -0,0 +1,84 @@ +--- +title: Document.scripts +slug: Web/API/Document/scripts +translation_of: Web/API/Document/scripts +--- +
+
{{ ApiRef("DOM") }}
+
+ +

Retorna uma lista dos elementos {{HTMLElement("script")}} no documento. O objeto retornado é um {{domxref("HTMLCollection")}}.

+ +

Sintaxe

+ +
var scriptList = document.scripts;
+
+ +

O scriptList retornado é um {{domxref("HTMLCollection")}}. Você pode usar isso apenas como um array para obter todos os elementos da lista.

+ +

Exemplo

+ +

Este exemplo é para ver se a página contém elementos {{HTMLElement("script")}}.

+ +
var scripts = document.scripts;
+
+if (scripts.length) {
+  alert("This page has scripts!");
+}
+
+ +

Compatibilidade do navegador

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop("9.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatGeckoMobile("9.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Especificação

+ + diff --git a/files/pt-br/web/api/document/url/index.html b/files/pt-br/web/api/document/url/index.html new file mode 100644 index 0000000000..e4a1d2eab7 --- /dev/null +++ b/files/pt-br/web/api/document/url/index.html @@ -0,0 +1,19 @@ +--- +title: Document.URL +slug: Web/API/Document/URL +translation_of: Web/API/Document/URL +--- +
{{APIRef("DOM")}}
+ +

A propriedade URL (usada apenas para leitura) da Interface {{domxref("Document")}} retorna a URL atual do navegador como um texto (string).

+ +

Síntaxe

+ +
var url_atual = document.URL
+
+ +

Documentação

+ + diff --git a/files/pt-br/web/api/document/write/index.html b/files/pt-br/web/api/document/write/index.html new file mode 100644 index 0000000000..4218430e88 --- /dev/null +++ b/files/pt-br/web/api/document/write/index.html @@ -0,0 +1,108 @@ +--- +title: Document.write() +slug: Web/API/Document/write +tags: + - API + - DOM + - Method + - Reference +translation_of: Web/API/Document/write +--- +
{{ApiRef("DOM")}}
+ +

O método Document.write() grava uma sequência de caracteres em um documento aberto por {{domxref("document.open()")}}.

+ +
Nota: à medida que document.write grava no fluxo de documentos, chamando document.write em um documento fechado (carregado) invoca automaticamente document.open, que limpará o documento.
+ +

Sintaxe

+ +
document.write(markup);
+
+ +

Parametros

+ +
+
markup
+
Uma string contendo o texto a ser gravado no documento.
+
+ +

Exemplo

+ +
<html>
+
+<head>
+  <title>Escreva exemplo</title>
+
+  <script>
+    function newContent() {
+      document.open();
+      document.write("<h1>Sair com o velho - entrar com o novo!</h1>");
+      document.close();
+    }
+  </script>
+</head>
+
+<body onload="newContent();">
+  <p>Algum conteúdo do documento original.</p>
+</body>
+
+</html>
+
+ +

{{EmbedLiveSample("Syntax")}}

+ +

Notas

+ +

Escrevendo em um documento que já foi carregado sem chamar {{domxref("document.open()")}} automaticamente vai chamar document.open. Ao términno da escrita, é recomendável chamar {{domxref("document.close()")}} para dizer ao navegador para encerrar o carregamento da página. O texto que você escreve é analisado no modelo de estrutura do documento. No exemplo acima, o elemento h1 se torna um nó (node) no documento.

+ +

Se chamar document.write() incorporada em uma tag HTML <script> embutida, então document.open() não será chamada. Por exemplo:

+ +
<script>
+  document.write("<h1>Título principal</h1>")
+</script>
+
+ +
Nota: document.write e {{domxref("document.writeln")}} não funcionam em documentos XHTML (você receberá o erro "Operation is not supported" [NS_ERROR_DOM_NOT_SUPPORTED_ERR] no console de erros). Isso acontece ao abrir um arquivo local com a extensão .xhtml ou em qualquer documento exibido com um MIME type application/xhtml+xml {{Glossary("MIME type")}}. Mais informações disponíveis em W3C XHTML FAQ.
+ +
Nota: document.write em deferred ou asynchronous scripts será ignorado, e você receberá uma mensagem como "A call to document.write() from an asynchronously-loaded external script was ignored" no console de erros.
+ +
Nota: Somente no Edge, chamando document.write mais de uma vez em {{HTMLElement("iframe")}} causa o erro "SCRIPT70: Permission denied".
+ +
Nota: A partir de 55, Chrome não executará elementos <script> injetados via document.write() caso haja falta de cache HTTP para usuários em uma conexão 2G. Há uma lista de condições que precisam ser atendidas para que isso seja verdade.
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + +
EspecificaçõesStatusComentario
{{SpecName("HTML WHATWG", "#dom-document-write", "document.write(...)")}}{{Spec2("HTML WHATWG")}}
{{SpecName("DOM2 HTML", "html.html#ID-75233634", "document.write(...)")}}{{Spec2("DOM2 HTML")}}
+ +

Compatibilidade de Browser

+ + + +
{{Compat("api.Document.write")}}
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/document/writeln/index.html b/files/pt-br/web/api/document/writeln/index.html new file mode 100644 index 0000000000..ed2efb2b85 --- /dev/null +++ b/files/pt-br/web/api/document/writeln/index.html @@ -0,0 +1,43 @@ +--- +title: Document.writeln() +slug: Web/API/Document/writeln +tags: + - API + - DOM + - Gecko + - Referencia + - metodo +translation_of: Web/API/Document/writeln +--- +
{{ ApiRef("DOM") }}
+ +

Grava uma seqüência de texto, seguido por um caractere de nova linha a um documento.

+ +

Sintaxes

+ +
document.writeln(line);
+
+ +

Parâmetros

+ + + +

Exemplo

+ +
document.writeln("<p>enter password:</p>");
+
+ +

Notas

+ +

document.writeln é o mesmo que document.write mas acrescenta uma nova linha.

+ +
Note: document.writeln (like document.write) does not work in XHTML documents (you'll get a "Operation is not supported" (NS_ERROR_DOM_NOT_SUPPORTED_ERR) error on the error console). This is the case if opening a local file with a .xhtml file extension or for any document served with an application/xhtml+xml MIME type. More information is available in the W3C XHTML FAQ.
+ +

Especificação

+ +

writeln

-- cgit v1.2.3-54-g00ecf