From 1109132f09d75da9a28b649c7677bb6ce07c40c0 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:41:45 -0500 Subject: initial commit --- files/es/web/api/document/abrir/index.html | 109 ++++++ files/es/web/api/document/adoptnode/index.html | 61 ++++ files/es/web/api/document/alinkcolor/index.html | 36 ++ files/es/web/api/document/anchors/index.html | 95 +++++ files/es/web/api/document/applets/index.html | 30 ++ files/es/web/api/document/async/index.html | 33 ++ files/es/web/api/document/bgcolor/index.html | 39 +++ files/es/web/api/document/body/index.html | 39 +++ files/es/web/api/document/characterset/index.html | 36 ++ files/es/web/api/document/clear/index.html | 31 ++ files/es/web/api/document/close/index.html | 27 ++ files/es/web/api/document/contenttype/index.html | 25 ++ files/es/web/api/document/crearatributo/index.html | 91 +++++ .../api/document/createdocumentfragment/index.html | 119 +++++++ files/es/web/api/document/createelement/index.html | 180 ++++++++++ .../es/web/api/document/createelementns/index.html | 168 +++++++++ files/es/web/api/document/createrange/index.html | 42 +++ .../es/web/api/document/createtextnode/index.html | 78 +++++ files/es/web/api/document/defaultview/index.html | 35 ++ files/es/web/api/document/designmode/index.html | 56 +++ files/es/web/api/document/dir/index.html | 76 ++++ files/es/web/api/document/doctype/index.html | 65 ++++ .../es/web/api/document/documentelement/index.html | 42 +++ files/es/web/api/document/documenturi/index.html | 121 +++++++ .../web/api/document/documenturiobject/index.html | 39 +++ .../es/web/api/document/dragover_event/index.html | 338 ++++++++++++++++++ files/es/web/api/document/embeds/index.html | 48 +++ files/es/web/api/document/evaluate/index.html | 211 +++++++++++ files/es/web/api/document/execcommand/index.html | 288 +++++++++++++++ .../es/web/api/document/exitfullscreen/index.html | 75 ++++ .../es/web/api/document/getelementbyid/index.html | 200 +++++++++++ .../api/document/getelementsbyclassname/index.html | 96 +++++ .../web/api/document/getelementsbyname/index.html | 81 +++++ .../api/document/getelementsbytagname/index.html | 104 ++++++ .../api/document/getelementsbytagnamens/index.html | 107 ++++++ files/es/web/api/document/getselection/index.html | 12 + files/es/web/api/document/hasfocus/index.html | 23 ++ files/es/web/api/document/head/index.html | 83 +++++ files/es/web/api/document/height/index.html | 44 +++ files/es/web/api/document/hidden/index.html | 43 +++ files/es/web/api/document/importnode/index.html | 84 +++++ files/es/web/api/document/index.html | 390 +++++++++++++++++++++ files/es/web/api/document/keydown_event/index.html | 178 ++++++++++ files/es/web/api/document/keyup_event/index.html | 149 ++++++++ .../web/api/document/pointerlockelement/index.html | 105 ++++++ files/es/web/api/document/queryselector/index.html | 136 +++++++ .../web/api/document/queryselectorall/index.html | 179 ++++++++++ files/es/web/api/document/readystate/index.html | 104 ++++++ .../es/web/api/document/registerelement/index.html | 115 ++++++ files/es/web/api/document/scripts/index.html | 84 +++++ files/es/web/api/document/scroll_event/index.html | 104 ++++++ files/es/web/api/document/stylesheets/index.html | 21 ++ files/es/web/api/document/url/index.html | 71 ++++ files/es/web/api/document/write/index.html | 76 ++++ files/es/web/api/document/writeln/index.html | 40 +++ 55 files changed, 5262 insertions(+) create mode 100644 files/es/web/api/document/abrir/index.html create mode 100644 files/es/web/api/document/adoptnode/index.html create mode 100644 files/es/web/api/document/alinkcolor/index.html create mode 100644 files/es/web/api/document/anchors/index.html create mode 100644 files/es/web/api/document/applets/index.html create mode 100644 files/es/web/api/document/async/index.html create mode 100644 files/es/web/api/document/bgcolor/index.html create mode 100644 files/es/web/api/document/body/index.html create mode 100644 files/es/web/api/document/characterset/index.html create mode 100644 files/es/web/api/document/clear/index.html create mode 100644 files/es/web/api/document/close/index.html create mode 100644 files/es/web/api/document/contenttype/index.html create mode 100644 files/es/web/api/document/crearatributo/index.html create mode 100644 files/es/web/api/document/createdocumentfragment/index.html create mode 100644 files/es/web/api/document/createelement/index.html create mode 100644 files/es/web/api/document/createelementns/index.html create mode 100644 files/es/web/api/document/createrange/index.html create mode 100644 files/es/web/api/document/createtextnode/index.html create mode 100644 files/es/web/api/document/defaultview/index.html create mode 100644 files/es/web/api/document/designmode/index.html create mode 100644 files/es/web/api/document/dir/index.html create mode 100644 files/es/web/api/document/doctype/index.html create mode 100644 files/es/web/api/document/documentelement/index.html create mode 100644 files/es/web/api/document/documenturi/index.html create mode 100644 files/es/web/api/document/documenturiobject/index.html create mode 100644 files/es/web/api/document/dragover_event/index.html create mode 100644 files/es/web/api/document/embeds/index.html create mode 100644 files/es/web/api/document/evaluate/index.html create mode 100644 files/es/web/api/document/execcommand/index.html create mode 100644 files/es/web/api/document/exitfullscreen/index.html create mode 100644 files/es/web/api/document/getelementbyid/index.html create mode 100644 files/es/web/api/document/getelementsbyclassname/index.html create mode 100644 files/es/web/api/document/getelementsbyname/index.html create mode 100644 files/es/web/api/document/getelementsbytagname/index.html create mode 100644 files/es/web/api/document/getelementsbytagnamens/index.html create mode 100644 files/es/web/api/document/getselection/index.html create mode 100644 files/es/web/api/document/hasfocus/index.html create mode 100644 files/es/web/api/document/head/index.html create mode 100644 files/es/web/api/document/height/index.html create mode 100644 files/es/web/api/document/hidden/index.html create mode 100644 files/es/web/api/document/importnode/index.html create mode 100644 files/es/web/api/document/index.html create mode 100644 files/es/web/api/document/keydown_event/index.html create mode 100644 files/es/web/api/document/keyup_event/index.html create mode 100644 files/es/web/api/document/pointerlockelement/index.html create mode 100644 files/es/web/api/document/queryselector/index.html create mode 100644 files/es/web/api/document/queryselectorall/index.html create mode 100644 files/es/web/api/document/readystate/index.html create mode 100644 files/es/web/api/document/registerelement/index.html create mode 100644 files/es/web/api/document/scripts/index.html create mode 100644 files/es/web/api/document/scroll_event/index.html create mode 100644 files/es/web/api/document/stylesheets/index.html create mode 100644 files/es/web/api/document/url/index.html create mode 100644 files/es/web/api/document/write/index.html create mode 100644 files/es/web/api/document/writeln/index.html (limited to 'files/es/web/api/document') diff --git a/files/es/web/api/document/abrir/index.html b/files/es/web/api/document/abrir/index.html new file mode 100644 index 0000000000..13b541561d --- /dev/null +++ b/files/es/web/api/document/abrir/index.html @@ -0,0 +1,109 @@ +--- +title: Document.open() +slug: Web/API/Document/abrir +translation_of: Web/API/Document/open +--- +
{{APIRef("DOM")}}
+ +

El método Document.open() abre un documento para escritura (writing)

+ +

Esto viene con algunos efectos secundarios. Por ejemplo:

+ + + +

Sintaxis

+ +
document.open();
+
+ +

Parametros

+ +

Ninguno.

+ +

Valor devuelto

+ +

Una instancia del objeto Document (Document).

+ +

Ejemplos

+ +

El código simple a continuación abre el documento y reemplaza su contenido con un número de diferentes fragmentos HTML antes de cerrarlo nuevamente.

+ +
document.open();
+document.write("<p>Hola mundo!</p>");
+document.write("<p>Soy un pez</p>");
+document.write("<p>El numero es 42</p>");
+document.close();
+ +

Notas

+ +
+

Traducción pendiente para el texto que sigue

+
+ +

An automatic document.open() call happens when {{domxref("document.write()")}} is called after the page has loaded.

+ +

For years Firefox and Internet Explorer additionally erased all JavaScript variables, etc., in addition to removing all nodes. This is no longer the case.document non-spec'ed parameters to document.open

+ +

Gecko-specific notes

+ +

Starting with Gecko 1.9, this method is subject to the same same-origin policy as other properties, and does not work if doing so would change the document's origin.

+ +

Starting with Gecko 1.9.2, document.open() uses the principal of the document whose URI it uses, instead of fetching the principal off the stack. As a result, you can no longer call {{domxref("document.write()")}} into an untrusted document from chrome, even using wrappedJSObject. See Security check basics for more about principals.

+ +

Three-argument document.open()

+ +

There is a lesser-known and little-used three-argument version of document.open() , which is an alias of {{domxref("Window.open()")}} (see its page for full details).

+ +

This call, for example opens github.com in a new window, with its opener set to null:

+ +
document.open('https://www.github.com','', 'noopener=true')
+ +

Two-argument document.open()

+ +

Browsers used to support a two-argument document.open(), with the following signature:

+ +
document.open(type, replace)
+ +

Where type specified the MIME type of the data you are writing (e.g. text/html) and replace if set (i.e. a string of "replace") specified that the history entry for the new document would replace the current history entry of the document being written to.

+ +

This form is now obsolete; it won't throw an error, but instead just forwards to document.open() (i.e. is the equivalent of just running it with no arguments).  The history-replacement behavior now always happens.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "#dom-document-open", "document.open()")}}{{Spec2("HTML WHATWG")}}
{{SpecName("DOM2 HTML", "html.html#ID-72161170", "document.open()")}}{{Spec2("DOM2 HTML")}}
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/es/web/api/document/adoptnode/index.html b/files/es/web/api/document/adoptnode/index.html new file mode 100644 index 0000000000..0a90679756 --- /dev/null +++ b/files/es/web/api/document/adoptnode/index.html @@ -0,0 +1,61 @@ +--- +title: Document.adoptNode() +slug: Web/API/Document/adoptNode +tags: + - API + - DOM + - DOM Reference + - Referencia + - metodo +translation_of: Web/API/Document/adoptNode +--- +
{{ ApiRef("DOM") }}
+ +

Document.adoptNode() transfiere un {{Glossary("node/dom", "node")}} desde otro {{domxref("Document", "document", "", "1")}} al documento del método. El nodo adoptado y sus subnodos se eliminan del documento original (si lo hubiera), encuentra  y su {{domxref("Node.ownerDocument", "ownerDocument")}} se cambia por el documento actual. El nodo puede entoces ser insertado en el documento actual.

+ +

Sintaxis

+ +
node = document.adoptNode(externalNode);
+
+ +
+
node
+
El nodo adoptado que ahora tiene este documento como su {{domxref("Node.ownerDocument", "ownerDocument")}}. El {{domxref("Node.parentNode", "parentNode")}} del nodo es null, esto se debe a que aún no a sido insertado en el árbol del documento. Tenga en cuenta que node y externalNode son el mismo objeto después de esta llamada.
+
externalNode
+
El nodo a ser adoptado desde otro documento.
+
+ +

Ejemplo

+ +
var iframe = document.querySelector('iframe');
+var iframeImages = iframe.contentDocument.querySelectorAll('img');
+var newParent = document.getElementById('images');
+
+iframeImages.forEach(function(imgEl) {
+  newParent.appendChild(document.adoptNode(imgEl));
+});
+
+ +

Notas

+ +

Los nodos de documentos externos deberían ser clonados utilizando {{domxref("document.importNode()")}} (o adoptado utilizando document.adoptNode()) antes de que puedan ser insertados en el documento actual. Para más incidencias sobre {{domxref("Node.ownerDocument")}}, vea el W3C DOM FAQ.

+ +

Firefox actualmente no obliga a cumplir esta regla (lo hizo un tiempo durante el desarrollo de Firefox 3, pero muchos sitios se rompían cuando esta regla era obligatoria). Animamos a los desarrolladores web a que corrijan su código para seguir esta regla con el fin de mejorar la compatibilidad futura.

+ +

Epecificación

+ + + +

Compatibilidad con navegadores

+ + + +

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

+ +

Vea también

+ + diff --git a/files/es/web/api/document/alinkcolor/index.html b/files/es/web/api/document/alinkcolor/index.html new file mode 100644 index 0000000000..f270799c53 --- /dev/null +++ b/files/es/web/api/document/alinkcolor/index.html @@ -0,0 +1,36 @@ +--- +title: document.alinkColor +slug: Web/API/Document/alinkColor +translation_of: Web/API/Document/alinkColor +--- +

{{APIRef("DOM")}}

+ +
+

Desaprobado

+
+ +

Devuelve o define el color que tendrán los vínculos activos en el cuerpo (elemento body del documento. Un vínculo está activo durante el tiempo entre los eventos mousedown (cuando se presiona el botón izquierdo del "mouse" sobre el vínculo) y mouseup (cuando se deja de presionar el vínculo al soltar el botón izquierdo del "mouse").

+ +

Sintaxis

+ +
color = document.alinkColor
+document.alinkColor =color
+
+ +

color es un texto que deberá llevar el nombre del color en inglés(e.g., "blue", "darkblue", etc.) o el valor hexadecimal del color (e.g., #0000FF)

+ +

Notas

+ +

El valor por defecto de esta propiedad en Mozilla es rojo (#ee0000 en hexadecimal).

+ +

document.alinkColor es obsoleto en DOM Level 2 HTML. Una alternativa es el selector CSS {{ Cssxref(":active") }}.

+ +

Otra alternativa es document.body.aLink, sin embargo éste es desaprobado en HTML 4.01 a favor de la alternativa CSS.

+ +

Gecko soporta tanto alinkColor/:active como {{ Cssxref(":focus") }}. Internet Explorer 6 y 7 soportan alinkColor/:active sólo para vínculos de ancla (<a>) HTML y el comportamiento es el mismo que :focus bajo Gecko. En IE (Internet Explorer) no hay soporte para :focus.

+ +

Especificación

+ +

DOM Nivel 0. No es parte de ningún estándar.

+ +

MSDN: alinkColor property

diff --git a/files/es/web/api/document/anchors/index.html b/files/es/web/api/document/anchors/index.html new file mode 100644 index 0000000000..fbcd8eea0e --- /dev/null +++ b/files/es/web/api/document/anchors/index.html @@ -0,0 +1,95 @@ +--- +title: document.anchors +slug: Web/API/Document/anchors +tags: + - API + - Desaprobado + - Documento + - HTML DOM + - Propiedad + - Referencia +translation_of: Web/API/Document/anchors +--- +
{{APIRef("DOM")}}{{deprecated_header()}}
+ +
La propiedad de solo lectura anchors de la interfaz {{domxref("Document")}} devuelve una lista de todas las anclas (anchors) del documento.
+ +

Sintaxis

+ +
nodeList = document.anchors;
+
+ +

Valor

+ +

Una {{domxref("HTMLCollection")}}.

+ +

Ejemplo

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

Lo siguiente es un ejemplo que puebla una Tabla de Contenido con cada ancla en la 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>
+ +

Ver en JSFiddle

+ +

Notas

+ +

Por razones de retrocompatibilidad, el conjunto de anclas devuelto sólo contiene aquellas anclas creadas con el atribuo name, y no aquellas creadas con el atributo id.

+ +

Especificaciones

+ +

DOM Level 2 HTML: anchors

+ +

{{ languages( { "en": "en/DOM/document.anchors", "pl": "pl/DOM/document.anchors", "ja": "ja/DOM/document.anchors" } ) }}

+ +

Compatibilidad de navegadores

+ + + +
{{Compat("api.Document.anchors")}}
diff --git a/files/es/web/api/document/applets/index.html b/files/es/web/api/document/applets/index.html new file mode 100644 index 0000000000..e6ecf71b60 --- /dev/null +++ b/files/es/web/api/document/applets/index.html @@ -0,0 +1,30 @@ +--- +title: document.applets +slug: Web/API/Document/applets +translation_of: Web/API/Document/applets +--- +

{{APIRef("DOM")}}

+ +

Resumen

+ +

applets Devuelve una lista ordenada de los + + applets + del documento.

+ +

Sintaxis

+ +
nodeList = document.applets
+
+ +

Ejemplo

+ +
// ( Cuando sabes que el segundoapplet es el que quieres )
+my_java_app = document.applets[1];
+
+ +

Especificación

+ +

DOM Level 2 HTML: applets

+ +

{{ languages( { "en": "en/DOM/document.applets", "pl": "pl/DOM/document.applets" } ) }}

diff --git a/files/es/web/api/document/async/index.html b/files/es/web/api/document/async/index.html new file mode 100644 index 0000000000..132fd106e1 --- /dev/null +++ b/files/es/web/api/document/async/index.html @@ -0,0 +1,33 @@ +--- +title: Document.async +slug: Web/API/Document/async +translation_of: Web/API/XMLDocument/async +--- +

document.async es utilizado para indicar cuándo un llamado de  {{domxref("document.load")}} debe ser sincrónico o asincrónico. true es su valor por defecto, indicando que el documento se cargó asincrónicamente.

+ +

(Desde la versión 1.4 alpha es posible cargar documentos sincrónicamente)

+ +

Ejemplo

+ +
function loadXMLData(e) {
+  alert(new XMLSerializer().serializeToString(e.target)); // Devuelve los contenidos de querydata.xml como un string
+}
+
+var xmlDoc = document.implementation.createDocument("", "test", null);
+
+xmlDoc.async = false;
+xmlDoc.onload = loadXMLData;
+xmlDoc.load('querydata.xml');
+ +

Especificación

+ + + +

Véase también

+ + diff --git a/files/es/web/api/document/bgcolor/index.html b/files/es/web/api/document/bgcolor/index.html new file mode 100644 index 0000000000..7baf9c893b --- /dev/null +++ b/files/es/web/api/document/bgcolor/index.html @@ -0,0 +1,39 @@ +--- +title: document.bgColor +slug: Web/API/Document/bgColor +translation_of: Web/API/Document/bgColor +--- +

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

+ +

bgColor da/define el color de fondo (bgColor) del documento actual.

+ +

Sintaxis

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

Parámetros

+ + + +

Ejemplos

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

Notas

+ +

El valor por defecto de esta propiedad en Mozilla Firefox es blanco (#ffffff en hexadecimal).

+ +

document.bgColor está desaprobado en DOM Level 2 HTML. La alternativa recomendada es el uso del estilo background-color de CSS el cual puede ser accesado a través del DOM con document.body.style.backgroundColor. Otra alternativa es document.body.bgColor, sin embargo, ésta última también está desaprobada en HTML 4.01 a favor de la alternativa CSS.

+ +

Especificación

+ +

DOM Nivel 0. No es parte de ningún estándar.

+ +

{{ languages( { "en": "en/DOM/document.bgColor", "pl": "pl/DOM/document.bgColor" } ) }}

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

Resumen

+ +

Devuelve el nodo del <body> o el nodo del <frameset> del documento.

+ +

Sintaxis

+ +
objRef = document.body
+document.body =
+objRef
+
+ +

Ejemplo

+ +
// en 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 es el elemento que contiene el contenido para el documento. En documentos con contenidos <body>, devuelven el elemento <body>, y en documentos de marco de sistema, esto devuelve el elemento extremo <frameset>.

+ +

Aunque body es programable, colocando un nuevo cuerpo en un documento efectivamente quitará a todos los hijos actuales del elemento existente <body>.

+ +

Especificación

+ +

DOM Level 2 HTML: HTMLDocument.body

+ +

{{ languages( { "en": "en/DOM/document.body", "pl": "pl/DOM/document.body" } ) }}

diff --git a/files/es/web/api/document/characterset/index.html b/files/es/web/api/document/characterset/index.html new file mode 100644 index 0000000000..b4fb1e2551 --- /dev/null +++ b/files/es/web/api/document/characterset/index.html @@ -0,0 +1,36 @@ +--- +title: document.characterSet +slug: Web/API/Document/characterSet +translation_of: Web/API/Document/characterSet +--- +

{{ ApiRef("DOM") }}

+ +

Resumen

+ +

Devuelve la codificación de caracteres (conjunto de caracteres) usado en el documento.

+ +

Sintaxis

+ +
string = document.characterSet
+
+ +

Ejemplo

+ +
<button onclick="alert(document.characterSet);"
+>Mostrar conjunto de caracteres</button>
+// devuelve el conjunto de caracteres del documento, por ejemplo "ISO-8859-1 o UTF-8"
+
+ +

Notas

+ +

La codificación de caracteres es el conjunto de caracteres usados para interpretar el documento, el cual puede ser diferente a la codificación especificada por la página (el usuario puede omitir la codificación).

+ +

Para una lista completa de juegos/conjuntos de caracteres, visite: http://www.iana.org/assignments/character-sets.

+ +

Especificación

+ +

DOM Nivel 0. No es parte de ningún estándar.

+ +
 
+ +

{{ languages( { "en": "en/DOM/document.characterSet", "pl": "pl/DOM/document.characterSet" } ) }}

diff --git a/files/es/web/api/document/clear/index.html b/files/es/web/api/document/clear/index.html new file mode 100644 index 0000000000..6208e48885 --- /dev/null +++ b/files/es/web/api/document/clear/index.html @@ -0,0 +1,31 @@ +--- +title: Document.clear() +slug: Web/API/Document/clear +tags: + - API + - Document + - HTML DOM + - Method + - NeedsCompatTable + - NeedsExample + - NeedsMarkupWork + - NeedsSpectTable + - Referencia +translation_of: Web/API/Document/clear +--- +

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

+ +

Método que se usa en versiones anterior a las 1.0 de Mozilla para para limpiar el documento completo.

+ +

No hace nada en versiones más recientes basado en Mozilla así como en Internet Explorer y Netscape 4.

+ +

Síntaxis

+ +
document.clear()
+
+ +

Especificación

+ + diff --git a/files/es/web/api/document/close/index.html b/files/es/web/api/document/close/index.html new file mode 100644 index 0000000000..313678de2c --- /dev/null +++ b/files/es/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")}}

+ +

El método document.close() finaliza la escritura de un documento abierta con document.open().

+ +

Sintaxis

+ +
document.close();
+
+ +

Ejemplo

+ +
// Abrir un documento.
+// Escribir contenido en el documento.
+// Cerrar el documento.
+document.open();
+document.write("<p>El único contenido.</p>");
+document.close();
+
+ +

Especificación

+ +

DOM Level 2 HTML: close() Method

diff --git a/files/es/web/api/document/contenttype/index.html b/files/es/web/api/document/contenttype/index.html new file mode 100644 index 0000000000..f385843676 --- /dev/null +++ b/files/es/web/api/document/contenttype/index.html @@ -0,0 +1,25 @@ +--- +title: Document.contentType +slug: Web/API/Document/contentType +translation_of: Web/API/Document/contentType +--- +

{{ ApiRef("DOM") }}{{Non-standard_header}}

+ +

Devuelve el tipo MIME con el que el documento está siendo renderizado. Puede obtenerlo a partir de los encabezados HTTP (Headers) o de otras fuentes de información MIME, y puede ser afectado por conversiones automáticas inferidas tanto por el navegador como por cualquiera de sus extensiones.

+ +

Sintáxis

+ +
contentType = document.contentType;
+
+ +

contentType es una propiedad de sólo lectura.

+ +

Notas

+ +

Esta propiedad no es afectada por los tags meta.

+ +

Especificaciones

+ +

No estándar, sólo soportada por Gecko.

+ +

 

diff --git a/files/es/web/api/document/crearatributo/index.html b/files/es/web/api/document/crearatributo/index.html new file mode 100644 index 0000000000..22f769d577 --- /dev/null +++ b/files/es/web/api/document/crearatributo/index.html @@ -0,0 +1,91 @@ +--- +title: Document.createAttribute() +slug: Web/API/Document/crearAtributo +tags: + - Atributos + - Crear Atributo + - JavaScript + - Métodos +translation_of: Web/API/Document/createAttribute +--- +
{{ ApiRef("DOM") }}
+ +

El método Document.createAttribute() crea un nuevo nodo de tipo atributo (attr), y lo retorna. El objeto crea un nodo implementando la interfaz {{domxref("Attr")}}. El DOM no impone que tipo de atributos pueden ser agregados a un particular elemento de esta forma.

+ +
+

El texto pasado como parametro es convertido a minusculas.

+
+ +

Sintaxis

+ +
atributo = document.createAttribute(nombre)
+
+ +

Parametros

+ + + +

Valor que retorna

+ +

Un nodo {{domxref("Attr")}} nodo.

+ +

Excepciones

+ + + +

Ejemplo

+ +
var nodo = document.getElementById("div1");
+var a = document.createAttribute("miAtributo");
+a.value = "nuevoVal";
+nodo.setAttributeNode(a);
+console.log(nodo.getAttribute("miAtributo")); // "nuevoVal"
+
+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaciónEstatusComentario
{{SpecName('DOM WHATWG','#dom-document-createattribute','Document.createAttribute()')}}{{Spec2("DOM WHATWG")}}Comportamiento preciso con caracteres en mayuscula 
{{SpecName('DOM3 Core','core.html#ID-1084891198','Document.createAttribute()')}}{{Spec2('DOM3 Core')}}Sin cambios
{{SpecName('DOM2 Core','core.html#ID-1084891198','Document.createAttribute()')}}{{Spec2('DOM2 Core')}}Sin cambios
{{SpecName('DOM1','level-one-core.html#ID-1084891198','Document.createAttribute()')}}{{Spec2('DOM1')}}Definición inicial
+ +

Compatibilidad del buscador

+ + + +

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

+ +

Ver ademas

+ + diff --git a/files/es/web/api/document/createdocumentfragment/index.html b/files/es/web/api/document/createdocumentfragment/index.html new file mode 100644 index 0000000000..5137778ee7 --- /dev/null +++ b/files/es/web/api/document/createdocumentfragment/index.html @@ -0,0 +1,119 @@ +--- +title: Document.createDocumentFragment() +slug: Web/API/Document/createDocumentFragment +translation_of: Web/API/Document/createDocumentFragment +--- +
{{ ApiRef("DOM") }}
+ +
+ +

Crea un nuevo DocumentFragment vacio, dentro del cual un nodo del DOM puede ser adicionado para construir un nuevo arbol DOM fuera de pantalla.

+ +

Sintaxis

+ +
var fragment = document.createDocumentFragment();
+
+ +

Se crea un objeto DocumentFragment vacio, el cual queda listo para que pueda insertarseles nodos en el.

+ +

Notas de uso

+ +

DocumentFragment son Nodos del DOM que nunca forman parte del arbol DOM. El caso de uso mas comun es crear un document fragment, agregar elementos al document fragment y luego agregar dicho document fragment al arbol del DOM. En el arbol del DOM, el document fragment es remplazado por todos sus hijos.

+ +

Dado que el document fragment es generado en memoria y no como parte del arbol del DOM, agregar elementos al mismo no causan reflow (computo de la posicion y geometria de los elementos) en la pagina. Como consecuencia, usar document fragments usualmente resultan en mejor performance.

+ +

Tambien puede utilizarse el constructor {{domxref("documentFragment")}} para crear un nuevo fragmento:

+ +
let fragment = new DocumentFragment();
+ +

Ejemplo

+ +

Este ejemplo crea una lista de los principales navegadores web en un DocumentFragment, y luego adiciona el nuevo subarbol DOM al document para ser mostrado.

+ +

HTML

+ +
<ul id="ul">
+</ul>
+ +

JavaScript

+ +
var element  = document.getElementById('ul'); // assuming ul exists
+var fragment = document.createDocumentFragment();
+var browsers = ['Firefox', 'Chrome', 'Opera',
+    'Safari', 'Internet Explorer'];
+
+browsers.forEach(function(browser) {
+    var li = document.createElement('li');
+    li.textContent = browser;
+    fragment.appendChild(li);
+});
+
+element.appendChild(fragment);
+ +

Resultado

+ +

{{EmbedLiveSample("Example", 600, 140)}}

+ +

Compatibilidad de navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Soporte Basico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Soporte Basico{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Especificaciónes

+ + + +

Vea También

+ + diff --git a/files/es/web/api/document/createelement/index.html b/files/es/web/api/document/createelement/index.html new file mode 100644 index 0000000000..cb7b3d175b --- /dev/null +++ b/files/es/web/api/document/createelement/index.html @@ -0,0 +1,180 @@ +--- +title: Document.createElement() +slug: Web/API/Document/createElement +tags: + - API + - DOM + - Documento + - Referencia + - metodo +translation_of: Web/API/Document/createElement +--- +
{{APIRef("DOM")}}
+ +

En un documento HTML, el método Document.createElement() crea un elemento HTML especificado por su tagName, o un  {{domxref("HTMLUnknownElement")}} si su tagName no se reconoce. En un documento XUL, crea el elemento XUL especificado. En otros documentos, crea un elemento con un namespace URI null.

+ +

Para declarar el namespace URI del elemento, utiliza document.createElementNS().

+ +

Sintaxis

+ +
var element = document.createElement(tagName, [options]);
+
+ +

Parámetros

+ +
+
tagName
+
+ +

Cadena que especifica el tipo de elemento a crear. El {{domxref("Node.nodeName", "nodeName")}} del elemento creado se inicializa con el valor de tagName. No utilizar nombres reservados (como "html:a") con este método. Al ser invocado en un documento HTML, createElement() convierte tagName a minúsculas antes de crear el elemento. En Firefox, Opera, y Chrome, createElement(null) funciona como createElement("null").

+ +
+
options{{optional_inline}}
+
Un objeto opcional ElementCreationOptions que contiene una única propiedad llamada is, cuyo valor es el de la etiqueta name de un elemento personalizado definido previamente utilizando customElements.define(). Para compatibilidad con versiones anteriores de Elements specification, algunos navegadores podrían permitir pasar una cadena aquí en vez de un objeto, donde el valor de la cadena es la etiqueta name del elemento creado. Ver Extending native HTML elements para más información sobre como usar este parámetro.
+
El nuevo elemento recibirá el atributo cuyo valor es la etiqueta name del elemento personalizado. Los elementos personalizados son una característica experimental solo disponible en algunos navegadores.
+
+ +

Retorna

+ +

El nuevo Element.

+ +

Ejemplo

+ +

Crea un nuevo <div> y lo inserta antes del elemento con ID "div1".

+ +

HTML

+ +
<!DOCTYPE html>
+<html>
+<head>
+  <title>||Trabajando con elementos||</title>
+</head>
+<body>
+  <div id="div1">El texto superior se ha creado dinámicamente.</div>
+</body>
+</html>
+
+ +

JavaScript

+ +
document.body.onload = addElement;
+
+function addElement () {
+  // crea un nuevo div
+  // y añade contenido
+  var newDiv = document.createElement("div");
+  var newContent = document.createTextNode("Hola!¿Qué tal?");
+  newDiv.appendChild(newContent); //añade texto al div creado.
+
+  // añade el elemento creado y su contenido al DOM
+  var currentDiv = document.getElementById("div1");
+  document.body.insertBefore(newDiv, currentDiv);
+}
+ +

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

+ +

Especificaciones

+ + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName('DOM WHATWG', "#dom-document-createelement", "Document.createElement")}}{{Spec2('DOM WHATWG')}}
+ +

Compatibilidad con navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Soporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}[1][2]{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Parámetro options{{CompatVersionUnknown}}[3]{{CompatUnknown}}{{CompatGeckoDesktop(50)}}[4][5]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Soporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

[1] Desde Gecko 22.0 {{geckoRelease("22.0")}} createElement() no utiliza {{domxref("HTMLSpanElement")}} interface cuando el argumento es "bgsounds", "multicol", o "image".  En cambio, HTMLUnknownElement se utiliza para "bgsound" y "multicol" y {{domxref("HTMLElement")}} HTMLElement se utiliza para "image".

+ +

[2] La implementación en Gecko de createElement no cumple la especificación DOM para documentos XUL y XHTML: localNamenamespaceURI no son inicializados como null en el elemento creado. Consúltese el {{ Bug(280692) }} para más información.

+ +

[3] En versiones anteriores de la especificación, este argumento era solamente una cadena cuyo valor era la etiqueta name del elemento personalizado. Por ejemplo: Podia recibir document.createElement("button", "mi-boton") en lugar de document.createElement("button", {id: "mi-boton"}). Por razones de compatibilidad, Chrome acepta ambas formas.

+ +

[4] Consultar [3] arriba: como Chrome, Firefox acepta una cadena en vez de un objeto en esta posición, pero solamente desde la versión 51 en adelante. En la versión 50, options debe ser un objeto.

+ +

[5] Para experimentar con elementos personalizados en Firefox, deben establecerse las preferencias dom.webcomponents.enabled y dom.webcomponents.customelements.enabled true.

+ +

Notas de CSS Quantum

+ + + +

Ver también

+ + diff --git a/files/es/web/api/document/createelementns/index.html b/files/es/web/api/document/createelementns/index.html new file mode 100644 index 0000000000..29571b0978 --- /dev/null +++ b/files/es/web/api/document/createelementns/index.html @@ -0,0 +1,168 @@ +--- +title: Document.createElementNS() +slug: Web/API/Document/createElementNS +translation_of: Web/API/Document/createElementNS +--- +
{{ApiRef("DOM")}}
+ +

Crea un elemento del DOM con el espacio de nombres URI y un nombre calificado.

+ +

Para crear un elemento sin especificar un espacio de nombre URI usa el método createElement.

+ +

Sintaxis

+ +
var element = document.createElementNS(namespaceURI, qualifiedName[, options]);
+
+ +

Parámetros

+ +
+
namespaceURI
+
String que especifica el namespace URI a asociar con el elemento. La propiedad namespaceURI del elemento creado es inicializada con el valor del namespaceURI. Ver Namespace URIs válidos.
+
qualifiedName
+
String que especifica el tipo del elemento a ser creado. La propiedad nodeName del elemento creado es inicializada con el valor qualifiedName.
+
optionsOpcional
+
Un objeto opcional ElementCreationOptions que contiene una sola propiedad llamada is, cuyo valor es el nombre de la etiqueta para un elemento personalizado previamente definido usando customElements.define(). Para retro compatibilidad con versiones previas de la Especificación de Elementos Personalizados, algunos navegadores te permitirán pasar un String aquí en lugar de un Objeto, donde el valor del String es el nombre de la etiqueta del elemento personalizado. Ver Extendiendo elementos HTML nativos para más información sobre como usar este parámetro.
+
Al nuevo elemento le será dado un atributo is cuyo valor es el nombre de la etiqueta del elemento personalizado. Los elementos personalizados son una característica experimental disponible solo en algunos navegadores.
+
+ +

Valor de Retorno

+ +

El nuevo Elemento.

+ +

Namespace URIs válidos

+ + + +

Ejemplo

+ +

El código siguiente crea un elemento <div> nuevo en el namespace XHTML y lo agrega al elemento vbox. Aunque no es un documento XUL extremamente útil esto demuestra el uso de los elementos de dos namespaces distintos dentro de un solo 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="||Trabajando con elementos||"
+      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 es el texto que fue construido dinámicamente con createElementNS y createTextNode y luego insertado dentro del documento usando appendChild.");
+   newdiv.appendChild(txtnode);
+   container.appendChild(newdiv);
+ }
+
+]]></script>
+
+ <vbox id='ContainerBox' flex='1'>
+  <html:div>
+   El script en esta página agregará contenido dinámico debajo:
+  </html:div>
+ </vbox>
+
+</page>
+
+ +
+

El ejemplo dado arriba usa script en linea lo cúal no es recomendable en documentos XHTML. Este ejemplo en particular es un documento XUL con XHTML embedido, de cualquier forma la recomendación aplica.

+
+ +

Especificaciones

+ + + + + + + + + + + + + + +
EspecificaciónEstatusComentario
{{SpecName('DOM WHATWG', "#dom-document-createelementns", "Document.createElement")}}{{Spec2('DOM WHATWG')}} 
+ +

Compatibilidad con navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
SoporteChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Soporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
argumento options {{CompatVersionUnknown}}[1]{{CompatGeckoDesktop(50)}}[2][3]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
SoporteAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Soporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

[1] En versiones previas de la especificación  el argumento fue solo un String cuyo valor fue el nombre de etiqueta del elemento personalizado. Por motivo de retro compatibilidad Chrome acepta ambas formas.

+ +

[2] Ver [1] arriba: Firefox al igual que Chrome acepta un string en lugar de un objeto, pero solo de la version 51 en adelante. En la version 50 options debe ser un objeto.

+ +

[3] Para experimentar con elementos personalizados en Firefox debes establecer las preferencias  dom.webcomponents.enabled y dom.webcomponents.customelements.enabled como true.

+ +

Ver también

+ + diff --git a/files/es/web/api/document/createrange/index.html b/files/es/web/api/document/createrange/index.html new file mode 100644 index 0000000000..8c0cc63391 --- /dev/null +++ b/files/es/web/api/document/createrange/index.html @@ -0,0 +1,42 @@ +--- +title: document.createRange +slug: Web/API/Document/createRange +tags: + - Rango + - Referencia_DOM_de_Gecko + - crear rango +translation_of: Web/API/Document/createRange +--- +

{{ ApiRef() }}

+ +

Resumen

+ +

Retorna un nuevo objeto Rango.

+ +

Sintáxis

+ +
range = document.createRange();
+
+ +

En este ejemplo, range es el nuevo objeto rango creado.

+ +

Ejemplo

+ +
var range = document.createRange();
+range.setStart(startNode, startOffset);
+range.setEnd(endNode, endOffset);
+
+ +

Notas

+ +

Una vez que se ha creado un objeto Rango, se necesita configurar sus puntos límites antes de hacer uso de la mayoría de sus métodos.

+ +

Especificación

+ +

DOM Level 2 Range: DocumentRange.createRange

+ + + +
+ +

{{ languages( { "en": "en/DOM/document.createRange", "pl": "pl/DOM/document.createRange" } ) }}

diff --git a/files/es/web/api/document/createtextnode/index.html b/files/es/web/api/document/createtextnode/index.html new file mode 100644 index 0000000000..fc1b1488f4 --- /dev/null +++ b/files/es/web/api/document/createtextnode/index.html @@ -0,0 +1,78 @@ +--- +title: Document.createTextNode() +slug: Web/API/Document/createTextNode +tags: + - API + - DOM + - Documento + - Referencia + - createTextNode + - metodo +translation_of: Web/API/Document/createTextNode +--- +
{{APIRef("DOM")}}
+ +

Crea un nuevo nodo de texto. Este método puede ser usado para escapar caracteres HTML.

+ +

Sintaxis

+ +
var text = document.createTextNode(data);
+
+ + + +

Ejemplo

+ +
<!DOCTYPE html>
+<html lang="en">
+<head>
+<title>createTextNode example</title>
+<script>
+function addTextNode(text) {
+  var newtext = document.createTextNode(text),
+      p1 = document.getElementById("p1");
+
+  p1.appendChild(newtext);
+}
+</script>
+</head>
+
+<body>
+  <button onclick="addTextNode('YES! ');">YES!</button>
+  <button onclick="addTextNode('NO! ');">NO!</button>
+  <button onclick="addTextNode('WE CAN! ');">WE CAN!</button>
+
+  <hr />
+
+  <p id="p1">First line of paragraph.</p>
+</body>
+</html>
+
+ +

Especificaciones

+ + + + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName('DOM WHATWG', '#dom-document-createtextnode', 'Document: createTextNode')}}{{Spec2('DOM WHATWG')}} 
+ +

Compatibilidad con navegadores

+ + + +

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

diff --git a/files/es/web/api/document/defaultview/index.html b/files/es/web/api/document/defaultview/index.html new file mode 100644 index 0000000000..e2b44cdd71 --- /dev/null +++ b/files/es/web/api/document/defaultview/index.html @@ -0,0 +1,35 @@ +--- +title: Document.defaultView +slug: Web/API/Document/defaultView +tags: + - API + - Document + - HTML DOM + - NeedsUpdate + - Property + - Reference +translation_of: Web/API/Document/defaultView +--- +
{{ ApiRef() }}
+ +

Resumen

+ +

En los navegadores devuelve el objeto window asociado con el document null si no está disponible.

+ +

Sintaxis

+ +
var win = document.defaultView;
+ +

Esta propiedad es de solo lectura.

+ +

Notas

+ +

De acuerco con quirksmode, defaultView no está soportado en IE hasta su version 9.

+ +

Especificación

+ + diff --git a/files/es/web/api/document/designmode/index.html b/files/es/web/api/document/designmode/index.html new file mode 100644 index 0000000000..cf234abee9 --- /dev/null +++ b/files/es/web/api/document/designmode/index.html @@ -0,0 +1,56 @@ +--- +title: Document.designMode +slug: Web/API/Document/designMode +tags: + - API + - Documento + - HTML DOM + - Propiedad + - Referencia + - editor +translation_of: Web/API/Document/designMode +--- +
{{ ApiRef() }}
+ +

document.designMode controla la posibilidad de editar un documento entero. Los valores válidos son "on" y "off". De acuerdo a las especificaciones,  el valor predeterminado de esta propiedad es "off". Firefox sigue este estándar. El valor predeterminado de versiones anteriores de Chrome y IE es "inherit". En IE6-10, el valor se escribe con mayúscula.

+ +

Sintaxis

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

Ejemplo

+ +

Hacer un documento {{HTMLElement("iframe")}} editable:

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

Especificaciones

+ + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName('HTML WHATWG', '#making-entire-documents-editable:-the-designmode-idl-attribute', 'designMode')}}{{Spec2('HTML WHATWG')}}Definición inicial.
+ +

Compatibilidad de Navegadores

+ +

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

+ +

Ver también

+ + diff --git a/files/es/web/api/document/dir/index.html b/files/es/web/api/document/dir/index.html new file mode 100644 index 0000000000..61c8a2d637 --- /dev/null +++ b/files/es/web/api/document/dir/index.html @@ -0,0 +1,76 @@ +--- +title: Document.dir +slug: Web/API/Document/dir +translation_of: Web/API/Document/dir +--- +

{{ApiRef("")}}{{non-standard_header}}

+ +

La propiedad Document.dir es una {{domxref("DOMString")}} que representa la dirección del texto del documento, ya sea de izquierda a derecha o de derecha a izquierda, siendo la primera el valor por defecto. Sus valores posibles son rtl (Right To Left) o ltr (Left To Right).

+ +

Sintáxis

+ +
dirStr = document.dir;
+document.dir = dirStr;
+
+ +

Especificaciones

+ +

HTML5 WHATWG

+ +

Compatibilidad de Navegadores

+ +

{{ CompatibilityTable() }}

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

[1] Antes de Firefox 23, la propiedad Document.dir devolvía "ltr" independientemente del valor de su elemento {{htmlelement("html")}} raíz.

+ +

Véase también

+ + diff --git a/files/es/web/api/document/doctype/index.html b/files/es/web/api/document/doctype/index.html new file mode 100644 index 0000000000..145ca57300 --- /dev/null +++ b/files/es/web/api/document/doctype/index.html @@ -0,0 +1,65 @@ +--- +title: Document.doctype +slug: Web/API/Document/doctype +tags: + - API + - DOCTYPE + - DOM + - Document + - Propiedad + - Referencia +translation_of: Web/API/Document/doctype +--- +
{{ApiRef("DOM")}}
+ +

Devuelve la Declaración de tipo de documento (Document Type Declaration (DTD)), asociada al documento actual. El objeto devuelto implementa la interfaz {{domxref("DocumentType")}}. Utilice {{domxref("DOMImplementation.createDocumentType()")}} para crear un DocumentType.

+ +

Sintaxis

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

Ejemplo

+ +
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

+ +

La propiedad devuelve null si no hay DTD asociada al documento actual.

+ +

El nivel 2 de DOM no soporta la edición de la declaración de tipo de documento.

+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName("DOM3 Core", "core.html#ID-B63ED1A31", "Document.doctype")}}{{Spec2("DOM3 Core")}}Cambiado el valor de retorno para documentos HTML sin el elemento {{HTMLElement("html")}}. Define que el tipo de documento puede ser modificado.
{{SpecName("DOM2 Core", "core.html#ID-B63ED1A31", "Document.doctype")}}{{Spec2("DOM2 Core")}}Definición inicial
diff --git a/files/es/web/api/document/documentelement/index.html b/files/es/web/api/document/documentelement/index.html new file mode 100644 index 0000000000..30453050f7 --- /dev/null +++ b/files/es/web/api/document/documentelement/index.html @@ -0,0 +1,42 @@ +--- +title: document.documentElement +slug: Web/API/Document/documentElement +tags: + - Referencia_DOM_de_Gecko +translation_of: Web/API/Document/documentElement +--- +

{{ ApiRef("DOM") }}

+ +

Resumen

+ +

Solo-lectura

+ +

Devuelve el Element que es el elemento raíz de document (por ejemplo, devuelve el elemento <html> en los documentos HTML).

+ +

Sintaxis

+ +
varelement = document.documentElement;
+
+ +

Ejemplo

+ +
var rootElement = document.documentElement;
+var firstTier = rootElement.childNodes;
+// firstTier el la NodeList de los hijos directos del elemento raízof the direct children of the root element
+for (var i = 0; i < firstTier.length; i++) {
+   // hacer algo con cada uno de los hijos directos del elemento raíz
+   // como firstTier[i]
+}
+
+ +

Notas

+ +

Esta propiedad es de sólo-lectura, facilitada para obtener el elemento raíz de cualquier documento.

+ +

Los documentos HTML contienen normalmente un único hijo directo, <html>, quizá con una declaración DOCTYPE antes que él. Los documento XML contienen a menudo, múltiples hijos: el elemento raíz, la declaración DOCTYPE y processing instructions.

+ +

Por tanto, deberías usar document.documentElement en lugar de {{ Domxref("document.firstChild") }} para obtener el elemento raíz.

+ +

Especificación

+ +

DOM Level 2 Core: Document.documentElement

diff --git a/files/es/web/api/document/documenturi/index.html b/files/es/web/api/document/documenturi/index.html new file mode 100644 index 0000000000..4ff365a258 --- /dev/null +++ b/files/es/web/api/document/documenturi/index.html @@ -0,0 +1,121 @@ +--- +title: Document.documentURI +slug: Web/API/Document/documentURI +tags: + - API + - ContenidoNecesario + - DOM + - EjemploNecesario + - Propiedad + - Referencia + - UbicaciónDocumento +translation_of: Web/API/Document/documentURI +--- +
{{ApiRef("DOM")}}
+ +

La propiedad documentURI de la interfaz del documento ({{domxref("Document")}}) devuelve la ubicación del documento como un string.

+ +

Originalmente DOM3 fue definido como un atributo de lectura/escritura. En DOM4 se especifica unicamente como de lectura.

+ +

Sintaxis

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

Notas

+ +

Los documentos HTML tienen una propiedad {{domxref("document.URL")}} la cual devuelve el mismo valor (ubicación del documento). A diferencia de URL, documentURI está disponible para todos los tipos de documentos web.

+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName('DOM4', '#dom-document-documenturi','documentURI')}}{{Spec2('DOM4')}} 
{{SpecName('DOM3 Core', '#Document3-documentURI', 'documentURI')}}{{Spec2('DOM3 Core')}}Definición inicial
+ +

Compatibilidad de navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Funcionamiento DOM3{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
Funcionamiento DOM4{{CompatChrome(43.0)}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Funcionamiento DOM3{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
Funcionamiento DOM4{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(43.0)}}
+
diff --git a/files/es/web/api/document/documenturiobject/index.html b/files/es/web/api/document/documenturiobject/index.html new file mode 100644 index 0000000000..fe28ca825f --- /dev/null +++ b/files/es/web/api/document/documenturiobject/index.html @@ -0,0 +1,39 @@ +--- +title: document.documentURIObject +slug: Web/API/Document/documentURIObject +tags: + - Referencia_DOM_de_Gecko +translation_of: Web/API/Document/documentURIObject +--- +

{{ ApiRef("DOM") }}

+ +

Resumen

+ +

Read-only

+ +

Devuelve un objeto {{ Interface("nsIURI") }} que representa la URI de document.

+ +

Esto sólo funciona para programas con privilegios (UniversalXPConnect) incluidas las extensiones. Para páginas web, esta propiedad no tiene significado especial y puede usarse de igual forma que cualquier otra propiedad del usuario.

+ +

El código con privilegios, debe tener cuidado de no leer o escribir esta propiedad en un objeto no controlado (e.g. on a wrappedJSObject of an XPCNativeWrapper). Ver {{ Bug(324464) }}para más detalles.

+ +

Sintaxis

+ +
varuri =doc.documentURIObject;
+
+ +

Ejemplo

+ +
// Comprueba que el esquema URI de la pestaña de Firefox es 'http',
+// asumiendo que este código se ejecuta dentro de browser.xul
+var uriObj = content.document.documentURIObject;
+var uriPort = uriObj.port;
+
+if (uriObj.schemeIs('http')) {
+  ...
+}
+
+ +

Especificación

+ +

No forma parte de ninguna especificación W3C.

diff --git a/files/es/web/api/document/dragover_event/index.html b/files/es/web/api/document/dragover_event/index.html new file mode 100644 index 0000000000..c4fe204135 --- /dev/null +++ b/files/es/web/api/document/dragover_event/index.html @@ -0,0 +1,338 @@ +--- +title: dragover +slug: Web/API/Document/dragover_event +translation_of: Web/API/Document/dragover_event +--- +
{{APIRef}}
+ +

El evento dragover se activa cuando un elemento o texto se arrastra a un objetivo válido (cada pocos cientos de milisegundos).

+ +

 

+ +

El evento se activa en la caída al objetivo.

+ +

General info

+ + + + + + + + + + + + + + + + + + + + + + + + +
BubblesYes
CancelableYes
Target objects{{domxref("Document")}}, {{domxref("Element")}}
Interface{{domxref("DragEvent")}}
Default ActionReset the current drag operation to "none".
+ +

Properties

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
target {{readonlyInline}}EventTargetEl elemento que se encontraba bajo el elemento que está siendo arrastrado.
type {{readonlyInline}}DOMStringEl tipo de evento.
bubbles {{readonlyInline}}BooleanSi el evento se propaga normalmente o no.
cancelable {{readonlyInline}}BooleanSi el evento es cancelable o no.
view {{readonlyInline}}WindowProxydocument.defaultView (window del documento)
detail {{readonlyInline}}long (float)0.
dataTransferDataTransferLos datos que subyacen a la operación de drag-and-drop , conocidas como drag data store. Modo protegido.
currentTarget {{readonlyInline}}EventTargetEl nodo que tiene adjunto el detector de eventos.
relatedTarget {{readonlyInline}}EventTargetPara los eventos de mouseover, mouseout, mouseenter y mouseleave:El objetivo del evento complementario (el objetivo mouseleave en el caso del evento mouseenter). null sino.
screenX {{readonlyInline}}longLa coordinada X del puntro del ratón en coordenadas globales (de pantalla).
screenY {{readonlyInline}}longLa coordinada Y del puntero del ratón en coordenadas globales (en pantalla).
clientX {{readonlyInline}}longLa coordinada X del puntro del ratón en coordenadas locales (DOM content).
clientY {{readonlyInline}}longLa coordinada Y del puntro del ratón en coordenadas locales (DOM content).
button {{readonlyInline}}unsigned short +

El número de botón que se preionó cuando el ecento fue ectivado: Botón izquierdo=0, botón del medio=1(en caso de que esté presente), botón derecho=2. Para ratones configurados para zurdos donde laas acciones están configuradas al contrario los valores se leerán de derecha a izquierda.

+
buttons {{readonlyInline}}unsigned short +

Los botones presionados cuando el evento de ratón se activa: botón izquierdo=1,botón derecho=2, botón medio (rueda)=4, 4º botón (tipo "hacia atrás del navegador"=8, 5º botón ("tipo hacia delante en el navegador"=16. Si dos o más botones se presionan, devolverá la suma lógica de los valores. Ej: si se presionan los botones izquierdo y derecho, devolverá 3 (=1|2). Más información.

+
mozPressure {{readonlyInline}}float +

La cantidad de presión aplicada en dispositivos táctiles cuando se genera el evento; Este valor tiene un rango entre 0.0 (mínima presión) y 1.0 (máxima presión)

+
ctrlKey {{readonlyInline}}booleantrue si la tecla control estaba pulsada cuando el evento se lanzó false en cualquier otro caso.
shiftKey {{readonlyInline}}booleantrue si la tecla shift estaba pulsada cuando el evento de lanzó. false en otro caso.
altKey {{readonlyInline}}booleantrue si la tecla alt estaba pulsada cuando el evento se lanzó. false si no.
metaKey {{readonlyInline}}booleantrue si la tecla meta estaba presionada cuando el evento se disparó. false si no.
+ +

Example

+ +
<div class="dropzone">
+  <div id="draggable" draggable="true" ondragstart="event.dataTransfer.setData('text/plain',null)">
+    This div is draggable
+  </div>
+</div>
+<div class="dropzone"></div>
+<div class="dropzone"></div>
+<div class="dropzone"></div>
+
+<style>
+  #draggable {
+    width: 200px;
+    height: 20px;
+    text-align: center;
+    background: white;
+  }
+
+  .dropzone {
+    width: 200px;
+    height: 20px;
+    background: blueviolet;
+    margin-bottom: 10px;
+    padding: 10px;
+  }
+</style>
+
+<script>
+  var dragged;
+
+  /* events fired on the draggable target */
+  document.addEventListener("drag", function( event ) {
+
+  }, false);
+
+  document.addEventListener("dragstart", function( event ) {
+      // store a ref. on the dragged elem
+      dragged = event.target;
+      // make it half transparent
+      event.target.style.opacity = .5;
+  }, false);
+
+  document.addEventListener("dragend", function( event ) {
+      // reset the transparency
+      event.target.style.opacity = "";
+  }, false);
+
+  /* events fired on the drop targets */
+  document.addEventListener("dragover", function( event ) {
+      // prevent default to allow drop
+      event.preventDefault();
+  }, false);
+
+  document.addEventListener("dragenter", function( event ) {
+      // highlight potential drop target when the draggable element enters it
+      if ( event.target.className == "dropzone" ) {
+          event.target.style.background = "purple";
+      }
+
+  }, false);
+
+  document.addEventListener("dragleave", function( event ) {
+      // reset background of potential drop target when the draggable element leaves it
+      if ( event.target.className == "dropzone" ) {
+          event.target.style.background = "";
+      }
+
+  }, false);
+
+  document.addEventListener("drop", function( event ) {
+      // prevent default action (open as link for some elements)
+      event.preventDefault();
+      // move dragged elem to the selected drop target
+      if ( event.target.className == "dropzone" ) {
+          event.target.style.background = "";
+          dragged.parentNode.removeChild( dragged );
+          event.target.appendChild( dragged );
+      }
+
+  }, false);
+</script>
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "interaction.html#dndevents", "dragover")}}{{Spec2("HTML WHATWG")}} 
{{SpecName("HTML5.1", "editing.html#dndevents", "dragover")}}{{Spec2("HTML5.1")}}Initial definition
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support4{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.1")}}10123.1
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatIE("10")}}{{CompatNo}}{{CompatNo}}
+
+ +

See also

+ + diff --git a/files/es/web/api/document/embeds/index.html b/files/es/web/api/document/embeds/index.html new file mode 100644 index 0000000000..865efdb2fd --- /dev/null +++ b/files/es/web/api/document/embeds/index.html @@ -0,0 +1,48 @@ +--- +title: Document.embeds +slug: Web/API/Document/embeds +tags: + - API + - Documento + - Ejemplo + - HTML DOM + - Propiedad +translation_of: Web/API/Document/embeds +--- +
{{ApiRef}}
+ +

embeds es una propiedad de sólo lectura de la interfaz de {{domxref("Document")}}. Devuelve una lista con los elementos {{htmlelement("object")}} incrustados dentro del documento actual.

+ +

Sintaxis

+ +
nodeList = document.embeds
+
+ +

Valor

+ +

Una {{domxref("HTMLCollection")}}.

+ +

Especificaciones

+ + + + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName('HTML WHATWG', '#dom-document-embeds', 'Document.embeds')}}{{ Spec2('HTML WHATWG') }}
+ +

Compatibilidad con Navegadores

+ + + +
{{Compat("api.Document.embeds")}}
diff --git a/files/es/web/api/document/evaluate/index.html b/files/es/web/api/document/evaluate/index.html new file mode 100644 index 0000000000..67bc5d432e --- /dev/null +++ b/files/es/web/api/document/evaluate/index.html @@ -0,0 +1,211 @@ +--- +title: Document.evaluate() +slug: Web/API/Document/evaluate +translation_of: Web/API/Document/evaluate +--- +
{{ ApiRef("DOM") }}
+ +

Retorna XPathResult basado en una expresión XPath y otros parametros dados .

+ +

Sintaxis

+ +
var xpathResult = document.evaluate(
+ xpathExpression,
+ contextNode,
+ namespaceResolver,
+ resultType,
+ result
+);
+ + + +

Ejemplo

+ +
var headings = document.evaluate("/html/body//h2", document, null, XPathResult.ANY_TYPE, null);
+/* Search the document for all h2 elements.
+ * The result will likely be an unordered node iterator. */
+var thisHeading = headings.iterateNext();
+var alertText = "Level 2 headings in this document are:\n";
+while (thisHeading) {
+  alertText += thisHeading.textContent + "\n";
+  thisHeading = headings.iterateNext();
+}
+alert(alertText); // Alerts the text of all h2 elements
+
+ +

Note, in the above example, a more verbose XPath is preferred over common shortcuts such as //h2. Generally, more specific XPath selectors as in the above example usually gives a significant performance improvement, especially on very large documents. This is because the evaluation of the query spends does not waste time visiting unnecessary nodes. Using // is generally slow as it visits every node from the root and all subnodes looking for possible matches.

+ +

Further optimization can be achieved by careful use of the context parameter. For example, if you know the content you are looking for is somewhere inside the body tag, you can use this:

+ +
document.evaluate(".//h2", document.body, null, XPathResult.ANY_TYPE, null);
+
+ +

Notice in the above document.body has been used as the context instead of document so the XPath starts from the body element. (In this example, the "." is important to indicate that the querying should start from the context node, document.body. If the "." was left out (leaving //h2) the query would start from the root node (html) which would be more wasteful.)

+ +

See Introduction to using XPath in JavaScript for more information.

+ +

Nota

+ + + +

Tipos de resultados

+ +

(Merge with Template:XPathResultConstants?

+ +

These are supported values for the resultType parameter of the evaluate method:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Result TypeValueDescription
ANY_TYPE0Whatever type naturally results from the given expression.
NUMBER_TYPE1A result set containing a single number. Useful, for example, in an XPath expression using the count() function.
STRING_TYPE2A result set containing a single string.
BOOLEAN_TYPE3A result set containing a single boolean value. Useful, for example, an an XPath expression using the not() function.
UNORDERED_NODE_ITERATOR_TYPE4A result set containing all the nodes matching the expression. The nodes in the result set are not necessarily in the same order they appear in the document.
ORDERED_NODE_ITERATOR_TYPE5A result set containing all the nodes matching the expression. The nodes in the result set are in the same order they appear in the document.
UNORDERED_NODE_SNAPSHOT_TYPE6A result set containing snapshots of all the nodes matching the expression. The nodes in the result set are not necessarily in the same order they appear in the document.
ORDERED_NODE_SNAPSHOT_TYPE7A result set containing snapshots of all the nodes matching the expression. The nodes in the result set are in the same order they appear in the document.
ANY_UNORDERED_NODE_TYPE8A result set containing any single node that matches the expression. The node is not necessarily the first node in the document that matches the expression.
FIRST_ORDERED_NODE_TYPE9A result set containing the first node in the document that matches the expression.
+ +

Results of NODE_ITERATOR types contain references to nodes in the document. Modifying a node will invalidate the iterator. After modifying a node, attempting to iterate through the results will result in an error.

+ +

Results of NODE_SNAPSHOT types are snapshots, which are essentially lists of matched nodes. You can make changes to the document by altering snapshot nodes. Modifying the document doesn't invalidate the snapshot; however, if the document is changed, the snapshot may not correspond to the current state of the document, since nodes may have moved, been changed, added, or removed.

+ +

Especificaciones

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("DOM3 XPath", "xpath.html#XPathEvaluator-evaluate", "Document.evaluate")}}{{Spec2("DOM3 XPath")}}Initial specification
+ +

Compatibilidad del navegador

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
XPath 1.0{{CompatChrome(1.0)}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(1.8)}}{{CompatNo}}{{CompatOpera(9.0)}}{{CompatVersionUnknown}}[1]
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
XPath 1.0{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Implemented in WebKit 5.0 (531) or earlier.

+ +

Ver también

+ + diff --git a/files/es/web/api/document/execcommand/index.html b/files/es/web/api/document/execcommand/index.html new file mode 100644 index 0000000000..2102597c22 --- /dev/null +++ b/files/es/web/api/document/execcommand/index.html @@ -0,0 +1,288 @@ +--- +title: Document.execCommand() +slug: Web/API/Document/execCommand +tags: + - API + - DOM + - Método(2) + - NecesitaEjemplo + - Referencia + - editor +translation_of: Web/API/Document/execCommand +--- +
{{ApiRef("DOM")}}
+ +

Resumen

+ +

Cuando un documento HTML se ha cambiado a designMode, el objeto de documento expone el método execCommand lo que permite ejecutar comandos para manipular el contenido de la región editable. La mayoría de los comandos afectan a la selección de documento (negrita, cursiva, etc.), mientras que otros insertar nuevos elementos (añadiendo un enlace) o afectan a toda una línea (sangría). Al usar contentEditable, la llamada a execCommand afectará el elemento editable activo actual.

+ +

Sintaxis

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

Parámetros

+ +
+
aCommandName
+
Una {{domxref("DOMString")}} que especifica el nombre del comando a ejecutar. Vea {{anch("Comandos")}} para una lista de posibles comandos.
+
aShowDefaultUI
+
Un {{jsxref("Boolean")}} que indica si la interfaz de usuario por defecto se debe mostrar. Esto no se ha implementado en Mozilla.
+
aValueArgument
+
Una {{domxref("DOMString")}} representando algunos comandos (como insertImage) requiere un argumento valor extra (url de la imagen). Pasar un argumento de null si no se necesita ningún argumento.
+
+ +

Comandos

+ +
+
backColor
+
 Cambia el color de fondo del documento. En el modo styleWithCss, afecta el color de fondo del bloque que contiene. Esto requiere una cadena con el valor del color de fondo que se pasa como un valor de argumento. (Internet Explorer utiliza esta opción para definir el color de fondo del texto.)
+
bold
+
Pone las negritas o las quita para la selección o en el punto de inserción. (Internet Explorer utiliza la etiqueta STRONG en lugar de B.)
+
contentReadOnly
+
Hace que el documento de contenido, ya sea de sólo lectura o editable. Esto requiere un booleano verdadero / falso que se pasa como un valor de argumento. (No es compatible con Internet Explorer.)
+
copy
+
Copia la selección actual en el portapapeles. Capacidad del Portapapeles debe estar habilitado en el archivo de preferencias user.js. Vea
+
createLink
+
Crea un vínculo de anclaje a partir de la selección, sólo si hay una selección. Esto requiere la cadena HREF URI que se pasa como un argumento de valor. El URI debe contener al menos un solo carácter, el cual puede ser un espacio en blanco. (Internet Explorer creará un enlace con un nulo valor URI.)
+
cut
+
Corta la selección y lo copia en el portapapeles actual. Capacidad del Portapapeles debe estar habilitado en el archivo de preferencias user.js. Vea
+
decreaseFontSize
+
Añade una etiqueta SMALL alrededor de la selección o en el punto de inserción. (No es compatible con Internet Explorer.)
+
delete
+
Elimina la selección actual.
+
enableInlineTableEditing
+
Activa o desactiva la fila de la tabla y los controles de inserción y supresión de columna. (No es compatible con Internet Explorer.)
+
enableObjectResizing
+
Activa o desactiva los controladores de tamaño en imágenes y otros objetos de tamaño variable. (No es compatible con Internet Explorer.)
+
fontName
+
Cambia el nombre de la fuente para la selección o en el punto de inserción. Esto requiere una cadena de nombre de la fuente ("Arial", por ejemplo) que se pasa como un valor de argumento.
+
fontSize
+
Cambia el tamaño de fuente para la selección o en el punto de inserción. Esto requiere un tamaño de fuente HTML (1-7) que se pasa como un valor de argumento.
+
foreColor
+
Cambia un color de fuente para la selección o en el punto de inserción. Esto requiere una cadena de valor de color que se pasa como un valor de argumento.
+
formatBlock
+
Añade una etiqueta HTML de estilo bloque alrededor de la línea que contiene la selección actual, reemplazando el elemento de bloque que contiene la línea si existe (en Firefox, BLOCKQUOTE es la excepción - que envolverá cualquier elemento de bloque que contiene). Requiere una cadena de etiqueta-nombre que se pasa como un argumento de valor. Prácticamente todas las etiquetas de estilo bloque se pueden utilizar (por ejemplo. "H1", "P", "DL", "BLOCKQUOTE"). (Internet Explorer sólo admite etiquetas de título H1 - H6, dirección y PRE, que también debe incluir los delimitadores de etiquetas <>, como "<H1>".)
+
forwardDelete
+
Elimina el character delante de la posición del cursor cursorEs lo mismo que pulsar la tecla suprimir.
+
heading
+
Añade una etiqueta de encabezado en torno a una selección, o la línea en el punto de inserción. Requiere la cadena de nombre de etiqueta que se pasa como un valor de argumento (es decir, "H1", "H6"). (No es compatible con Internet Explorer y Safari.)
+
hiliteColor
+
Cambia el color de fondo para la selección o el punto de inserción. Requiere una cadena de valores de color que se pasa como un valor de argumento. UseCSS debe estar encendido para que esto funcione. (No es compatible con Internet Explorer.)
+
increaseFontSize
+
Añade una etiqueta BIG alrededor de la selección o en el punto de inserción. (No es compatible con Internet Explorer.)
+
indent
+
Indenta la línea que contiene el punto de selección o inserción. En Firefox, si la selección abarca varias líneas en los diferentes niveles de indentación serán indentadas sólo las líneas menos indentadas en la selección.
+
insertBrOnReturn
+
Controla si la tecla Intro inserta una etiqueta br o divide el elemento de bloque actual en dos. (No es compatible con Internet Explorer.)
+
insertHorizontalRule
+
 Inserta una regla horizontal en el punto de inserción (borra la selección).
+
insertHTML
+
Inserta una cadena HTML en el punto de inserción (borra la selección). Requiere una cadena HTML válido que se ha pasado como un valor de argumento. (No es compatible con Internet Explorer.)
+
insertImage
+
Inserta una imagen en el punto de inserción (borra la selección). Requiere la cadena de imagen SRC URI que se pasa como un argumento de valor. El URI debe contener al menos un solo carácter, que puede ser un espacio en blanco. (Internet Explorer creará un enlace con un nulo valor URI.)
+
insertOrderedList
+
Crea una lista ordenada con números para la selección o en el punto de inserción.
+
insertUnorderedList
+
Crea una lista desordenada con viñetas para la selección o en el punto de inserción.
+
insertParagraph
+
  Inserta un párrafo en torno a la selección o la línea actual. (Internet Explorer inserta un párrafo en el punto de inserción y elimina la selección.)
+
insertText
+
Inserta el texto plano expedido en el punto de inserción (borra la selección).
+
italic
+
Alterna cursiva para la selección o el punto de inserción. (Internet Explorer utiliza la etiqueta de EM en lugar de I.)
+
justifyCenter
+
 Centra el punto de selección o inserción.
+
justifyFull
+
Justifica el punto de selección o inserción.
+
justifyLeft
+
Justifica la selección o inserción punto a la izquierda.
+
justifyRight
+
Justifica la selección o el punto de inserción a la derecha.
+
outdent
+
Anula la sangría de la línea que contiene la selección o el punto de inserción.
+
paste
+
Pega el contenido del portapapeles en el punto de inserción (reemplaza la selección actual). Capacidad del Portapapeles debe estar habilitado en el archivo de preferencias user.js. Ver
+
redo
+
Rehace el anterior comando deshecho.
+
removeFormat
+
Quita todo el formato de la selección actual.
+
selectAll
+
Selecciona todo el contenido de la región editable.
+
strikeThrough
+
Alterna tachado para la selección o el punto de inserción.
+
subscript
+
Alterna subíndice para la selección o el punto de inserción.
+
superscript
+
Alterna exponente para la selección o el punto de inserción.
+
underline
+
Alterna subrayado para la selección o el punto de inserción.
+
undo
+
Deshace el último comando ejecutado.
+
unlink
+
 Elimina la etiqueta de ancla de un enlace ancla seleccionado.
+
useCSS {{ Deprecated_inline() }}
+
Alterna el uso de etiquetas HTML o CSS para el marcado generado. Requiere un booleano verdadero / falso como valor del argumento. NOTA: Este argumento es lógicamente hacia atrás (es decir, si se usa falso a usar CSS, entonces es verdadero a usar HTML). (No compatible con Internet Explorer.) Esto ha quedado obsoleto; utilice el comando styleWithCSS en su lugar.
+
styleWithCSS
+
Reemplaza el comando useCSS; el argumento funciona como se esperaba, es decir, si es verdadero modifica / genera atributos de estilo en el marcado, falso genera elementos de formato.
+
+ +

Ejemplo

+ +

(Este artículo está actualmente incompleto y carece de un ejemplo.)

+ +

Compatibilidad del navegador

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Soporte básico{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatVersionUnknown() }}
insertBrOnReturn{{ CompatNo() }}{{ CompatVersionUnknown() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Soporte básico{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatVersionUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+ +

Consulte la Scribe's "Browser Inconsistencies" documentation para obtener una lista de los muchos errores del navegador relacionadas con document.execCommand.

+
+ +

Especificación

+ + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName('HTML Editing','#execcommand()','execCommand')}}{{Spec2('HTML Editing')}} 
+ +

Vea también

+ + diff --git a/files/es/web/api/document/exitfullscreen/index.html b/files/es/web/api/document/exitfullscreen/index.html new file mode 100644 index 0000000000..cd90147d82 --- /dev/null +++ b/files/es/web/api/document/exitfullscreen/index.html @@ -0,0 +1,75 @@ +--- +title: Document.exitFullscreen() +slug: Web/API/Document/exitFullscreen +translation_of: Web/API/Document/exitFullscreen +--- +
{{ApiRef("Fullscreen API")}}
+ +

El método exitFullscreen() de {{domxref("Document")}} solicita que el elemento de este documento que se presenta actualmente en modo de pantalla completa se retire del modo de pantalla completa, restaurando el estado anterior de la pantalla. Esto generalmente revierte los efectos de una llamada previa a {{domxref("Element.requestFullscreen()")}}.

+ +

La excepción es si otro elemento ya estaba en modo de pantalla completa cuando el elemento actual se colocó en modo de pantalla completa usando requestFullscreen(). En ese caso, el elemento de pantalla completa anterior se restaura al estado de pantalla completa. En esencia, se mantiene un {{interwiki("wikipedia", "Stack_(abstract_data_type)", "stack")}} de elementos de pantalla completa.

+ +

Sintaxis

+ +
exitPromise = document.exitFullscreen();
+
+ +

Parámetros

+ +

Ninguno.

+ +

Valor de retorno

+ +

Un {{jsxref("Promise")}} que se resuelve una vez que el {{Glossary("user agent")}} a terminado de salir del modo de pantalla completa. Si se produce un error al intentar salir del modo de pantalla completa, se llama al controlador catch() para la promesa.

+ +

Ejemplo

+ +

Este ejemplo hace que el documento actual entre y salga de una presentación a pantalla completa cada vez que se hace clic dentro del botón del mouse.

+ +
document.onclick = function (event) {
+  if (document.fullscreenElement) {
+    document.exitFullscreen()
+  } else {
+    document.documentElement.requestFullscreen()
+  }
+};
+ +
+

Nota: Para un ejemplo más completo, vea {{SectionOnPage("/en-US/docs/Web/API/Element/requestFullScreen", "Example")}}.

+
+ +

Especificaciones

+ + + + + + + + + + + + + + + + +
EspecificaciónEstadoComentarios
{{SpecName("Fullscreen", "#dom-document-exitfullscreen", "Document.exitFullscreen()")}}{{Spec2("Fullscreen")}}Definición inicial
+ +

Compatibilidad del navegador

+ + + +

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

+ +

Ver también

+ + diff --git a/files/es/web/api/document/getelementbyid/index.html b/files/es/web/api/document/getelementbyid/index.html new file mode 100644 index 0000000000..1232df45b4 --- /dev/null +++ b/files/es/web/api/document/getelementbyid/index.html @@ -0,0 +1,200 @@ +--- +title: document.getElementById +slug: Web/API/Document/getElementById +tags: + - API + - DOM + - Documento + - Elementos + - Referencia + - Web + - id + - metodo +translation_of: Web/API/Document/getElementById +--- +
{{ ApiRef("DOM") }}
+ +
 
+ +

Devuelve una referencia al elemento por su ID.

+ +

Sintaxis

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

Parámetros

+ +
+
id
+
Es una cadena sensible a mayúsculas referida al ID único del elemento buscado.
+
+ +

Valor Retornado

+ +
+
element
+
Es una referencia a un objeto {{domxref("Element")}}, o null si un elemento con el ID especificado no se encuentra en el documento.
+
+

Ejemplo

+ +

HTML

+ +
<html>
+<head>
+   <title>Ejemplo getElementById</title>
+</head>
+<body>
+   <p id="para">Cualquier texto acá</p>
+   <button onclick="changeColor('blue');">Azul</button>
+   <button onclick="changeColor('red');">Rojo</button>
+</body>
+</html>
+
+ +

JavaScript

+ +
function changeColor(newColor) {
+   var elem = document.getElementById('para');
+   elem.style.color = newColor;
+}
+
+ +

Resultado

+ +

{{EmbedLiveSample('Ejemplo', 250, 100)}}

+
+
+ +

Notas

+ +

Los usuarios nuevos deberían notar que escribir en mayúsculas 'Id' en el nombre de este método debe ser corregida para que el código sea válido - 'getElementByID' no funcionará a pesar de que parezca natural.

+ +

A diferencia de otros métodos similares, getElementById sólo está disponible como un método del objeto global document, y no se encuentra disponible como un método en todos los objetos  del DOM. Como los valores ID deben ser únicos a traves del documento, no existe necesidad para versiones "locales" de la función.

+ +

Ejemplo

+ +
<!doctype html>
+<html>
+<head>
+    <meta charset="UTF-8">
+    <title>Documento</title>
+</head>
+<body>
+    <div id="parent-id">
+        <p>Hola Mundo 1</p>
+        <p id="test1">Hola Mundo 2</p>
+        <p>Hola palabra 3</p>
+        <p>Hola palabra 4</p>
+    </div>
+    <script>
+        var parentDOM = document.getElementById('parent-id');
+        var test1=parentDOM.getElementById('test1');
+        //lanza error
+        //Uncaught TypeError: parentDOM.getElementById is not a function
+    </script>
+</body>
+</html>
+ +

Si no existe un elemento con la id solicitada, esta función devuelve null. Note que el parámetro id es sensible a mayúsculas, así que document.getElementById("Main") devolverá null dentro del elemento <div id="main"> porque "M" y "m" son diferentes para los propósitos de este método.

+ +

Elementos que no se encuentren en el documento no serán buscados por getElementById(). Cuando se cree un elemento y se le asigne un ID, debe insertar el elemento dentro del árbol del documento con {{domxref("Node.insertBefore()")}} u otro método similar antes de que se pueda acceder a el con getElementById():

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

Documentos no-HTML. La implementación de DOM debe tener información que diga que atributos son del tipo ID. Los atributos con el nombre "id" son son del tipo ID a menos que se los defina en el DTD del documento. El atributo id es definido para ser del tipo ID en los casos comunes de XHTML, XUL,  y otros. Las implementaciones que no sepan si los atributos son o no del tipo ID se espera que retornen null.

+ +

Especificación

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaciónStatusComentarios
{{SpecName('DOM1','level-one-html.html#method-getElementById','getElementById')}}{{Spec2('DOM1')}}Definición inicial para la interfase
{{SpecName('DOM2 Core','core.html#ID-getElBId','getElementById')}}{{Spec2('DOM2 Core')}}Supersede DOM 1
{{SpecName('DOM3 Core','core.html#ID-getElBId','getElementById')}}{{Spec2('DOM3 Core')}}Supersede DOM 2
{{SpecName('DOM WHATWG','#interface-nonelementparentnode','getElementById')}}{{Spec2('DOM WHATWG')}}Intend to supersede DOM 3
+ +

Compatibilidad con navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support1.0{{ CompatGeckoDesktop(1.0) }}5.57.01.0
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support1.0{{ CompatGeckoMobile(1.0) }}6.06.01.0
+
+ +

Ver también

+ + +
diff --git a/files/es/web/api/document/getelementsbyclassname/index.html b/files/es/web/api/document/getelementsbyclassname/index.html new file mode 100644 index 0000000000..b3a7179e4d --- /dev/null +++ b/files/es/web/api/document/getelementsbyclassname/index.html @@ -0,0 +1,96 @@ +--- +title: Document.getElementsByClassName() +slug: Web/API/Document/getElementsByClassName +translation_of: Web/API/Document/getElementsByClassName +--- +

{{APIRef("DOM")}}

+ +

Retorna un objecto similar a un array de los elementos hijos que tengan todos los nombres de clase indicados. Cuando es llamado sobre el objeto document , la busqueda se realiza en todo el document, incluido el nodo raíz. También puedes llamar {{domxref("Element.getElementsByClassName", "getElementsByClassName()")}} sobre cualquier elemento; en ese caso retornara sólo los elementos hijos del elemento raíz indicado que contengan los nombres de clase indicados.

+ +

Sintaxis

+ +
var elementos = document.getElementsByClassName(nombres); // ó :
+var elementos = elementoRaiz.getElementsByClassName(nombres);
+ + + +

Ejemplos

+ +

Obtener todos los elementos de la clase 'prueba'

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

Obtener todos los elementos que tengan al mismo tiempo las clases 'rojo' y 'prueba'

+ +
document.getElementsByClassName('rojo prueba');
+ +

Obtener todos los elementos que tengan la clase 'prueba' y que estén dentro de un elemento de ID 'principal'

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

También podemos usar los metodos de Array.prototype en cualquier {{ domxref("HTMLCollection") }} pasando el HTMLCollection como el valor this del método. Aquí buscaremos todos los elementos div de la clase 'test':

+ +
var testElements = document.getElementsByClassName('test');
+var testDivs = Array.prototype.filter.call(testElements, function(testElement){
+    return testElement.nodeName === 'DIV';
+});
+ +

Compatibilidad con navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }}3.09.0{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

Especifiación

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

Returns a nodelist collection with a given {{domxref("element.name","name")}} in the (X)HTML document.

+ +

Sintaxis

+ +
elements = document.getElementsByName(name)
+
+ + + +

Ejemplo

+ +
<!DOCTYPE html>
+<html lang="en">
+<head>
+ ...
+</head>
+
+<body>
+<form name="up"><input type="text"></form>
+<div name="down"><input type="text"></div>
+
+<script>
+var up_forms = document.getElementsByName("up");
+console.log(up_forms[0].tagName); // returns "FORM"
+</script>
+</body>
+</html>
+
+ +

Notas

+ +

El atributo name es solamente aplicable al documento (X)HTML. El método retorna una colección existente de {{domxref("NodeList")}} que contiene todos los elementos con el valor dado para el atributo name, tanto {{htmlelement("meta")}} o {{htmlelement("object")}} o en caso que name sea colocado en elementos que no soportan un atributo de atributo del todo.

+ +

El método getElementsByName trabaja de diferente manera en diferentes navegadires. En IE < 10, el método getElementsByName() tambipen retornará elementos que tienen un atributo id con el valor especificado. Entonces, debería tener cuidado de no usar el mismo string como name y ID.

+ +

Especificaciones

+ + + +

Especificaciones

+ + + + + + + + + + + + + + + + + + + +
EspecificacionesestadoComentario
{{SpecName('HTML WHATWG', '#dom-document-getelementsbyname', "Document.getElementsByName()")}}{{ Spec2('HTML WHATWG') }} 
{{SpecName("DOM2 HTML", "html.html#ID-71555259", "Document.getElementsByName()")}}{{Spec2("DOM2 HTML")}}Initial definition
+ +

Mira también

+ + diff --git a/files/es/web/api/document/getelementsbytagname/index.html b/files/es/web/api/document/getelementsbytagname/index.html new file mode 100644 index 0000000000..7be48858c0 --- /dev/null +++ b/files/es/web/api/document/getelementsbytagname/index.html @@ -0,0 +1,104 @@ +--- +title: document.getElementsByTagName +slug: Web/API/Document/getElementsByTagName +tags: + - Referencia_DOM_de_Gecko +translation_of: Web/API/Document/getElementsByTagName +--- +

{{ ApiRef("DOM") }}

+ +

Resumen

+ +

Devuelve una lista de elementos con un nombre determinado. Se busca en todo el documento, incluyendo el nodo raíz.

+ +

Sintaxis

+ +
elements = document.getElementsByTagName(name)
+
+ + + +

Ejemplo

+ +

En el siguiente ejemplo, getElementsByTagName empieza por el elemento padre y busca hacia abajo recurrentemente a lo largo de todo el DOM por ese elemento padre, buscando por hijos que cumplan con el criterio: nombre = name.

+ +

Ten en cuenta que cuando el nodo en el que se invoca getElementsByTagName, no es el nodo document, en realidad se está usando el método element.getElementsByTagName.

+ +
<html>
+
+<head>
+<title>ejemplo de getElementsByTagName</title>
+
+<script type="text/javascript">
+
+function getAllParaElems()
+{
+  var allParas = document.getElementsByTagName("p");
+
+  var num = allParas.length;
+
+  alert("Hay " + num + " <p> elementos en este documento");
+}
+
+
+function div1ParaElems()
+{
+  var div1 = document.getElementById("div1")
+  var div1Paras = div1.getElementsByTagName("p");
+
+  var num = div1Paras.length;
+
+  alert("Hay " + num + " <p> elementos en el elemento div1");
+}
+
+
+function div2ParaElems()
+{
+  var div2 = document.getElementById("div2")
+  var div2Paras = div2.getElementsByTagName("p");
+
+  var num = div2Paras.length;
+
+  alert("Hay " + num + " <p> elementos en el elemento div2");
+}
+
+</script>
+</head>
+
+<body style="border: solid green 3px">
+<p>Algo de texto</p>
+<p>Algo de texto</p>
+
+  <div id="div1" style="border: solid blue 3px">
+    <p>Algo de texto en div1</p>
+    <p>Algo de texto en div1</p>
+    <p>Algo de texto en div1</p>
+
+    <div id="div2" style="border: solid red 3px">
+    <p>Algo de texto en div2</p>
+    <p>Algo de texto en div2</p>
+    </div>
+  </div>
+
+<p>Algo de texto</p>
+<p>Algo de texto</p>
+
+<button onclick="getAllParaElems();">
+ muestra todos los elementos p en el documento</button><br />
+
+<button onclick="div1ParaElems();">
+ muestra todos los elementos p en div1</button><br />
+
+<button onclick="div2ParaElems();">
+ muestra todos los elementos p en div2</button>
+
+</body>
+</html>
+
+ +

Especificación

+ +

DOM Level 2 Core: Document.getElementsByTagName

diff --git a/files/es/web/api/document/getelementsbytagnamens/index.html b/files/es/web/api/document/getelementsbytagnamens/index.html new file mode 100644 index 0000000000..d97657647b --- /dev/null +++ b/files/es/web/api/document/getelementsbytagnamens/index.html @@ -0,0 +1,107 @@ +--- +title: document.getElementsByTagNameNS +slug: Web/API/Document/getElementsByTagNameNS +tags: + - Referencia_DOM_de_Gecko +translation_of: Web/API/Document/getElementsByTagNameNS +--- +

{{ ApiRef() }}

+ +

Resumen

+ +

Devuelve una lista de elementos cuyo nombre pertenece a un determinado 'namespace'. La búsqueda se realiza en todo el documento, incluyendo el elemento raíz.

+ +

Sintaxis

+ +
elements = document.getElementsByTagNameNS(namespace,name)
+
+ + + +

Ejemplo

+ +

En el siguiente ejemplo, getElementsByTagNameNS comienza por un elemento padre determinado y busca recurrentemente, hacia abajo, por los elementos que tienen el parámetro name que concuerda.

+ +

Es importante tener en cuenta que cuando el nodo en el que se invoca getElementsByTagName, no es el nodo document, en realidad estamos usando el método element.getElementsByTagNameNS.

+ +

Para usar el siguiente ejemplo, copia y pega en un documento con la extensión xhtml.

+ +
<html xmlns="http://www.w3.org/1999/xhtml">
+
+<head>
+<title>ejemplo de getElementsByTagNameNS</title>
+
+<script type="text/javascript">
+
+function getAllParaElems()
+{
+  var allParas = document.getElementsByTagNameNS("http://www.w3.org/1999/xhtml", "p");
+
+  var num = allParas.length;
+
+  alert("Hay " + num + " &lt;p&gt; elementos en este documento");
+}
+
+
+function div1ParaElems()
+{
+  var div1 = document.getElementById("div1")
+  var div1Paras = div1.getElementsByTagNameNS("http://www.w3.org/1999/xhtml", "p");
+
+  var num = div1Paras.length;
+
+  alert("Hay " + num + " &lt;p&gt; elementos en el elemento div1");
+}
+
+
+function div2ParaElems()
+{
+  var div2 = document.getElementById("div2")
+  var div2Paras = div2.getElementsByTagNameNS("http://www.w3.org/1999/xhtml", "p");
+
+  var num = div2Paras.length;
+
+  alert("Hay " + num + " &lt;p&gt; elementos en el elemento div2");
+}
+
+</script>
+</head>
+
+<body style="border: solid green 3px">
+<p>Algo de texto exterior</p>
+<p>Algo de texto exterior</p>
+
+  <div id="div1" style="border: solid blue 3px">
+    <p>Algo de texto en div1</p>
+    <p>Algo de texto en div1</p>
+    <p>Algo de texto en div1</p>
+
+    <div id="div2" style="border: solid red 3px">
+    <p>Algo de texto en div2</p>
+    <p>Algo de texto en div2</p>
+    </div>
+  </div>
+
+<p>Algo de texto exterior</p>
+<p>Algo de texto exterior</p>
+
+<button onclick="getAllParaElems();">
+ muestra todos los elementos p en el documento</button><br />
+
+<button onclick="div1ParaElems();">
+ muestra todos los elementos p en el div1</button><br />
+
+<button onclick="div2ParaElems();">
+ muestra todos los elementos p en el div2</button>
+
+</body>
+</html>
+
+ +

Especificación

+ +

DOM Level 2 Core: Document.getElementsByTagNameNS

diff --git a/files/es/web/api/document/getselection/index.html b/files/es/web/api/document/getselection/index.html new file mode 100644 index 0000000000..494ded4250 --- /dev/null +++ b/files/es/web/api/document/getselection/index.html @@ -0,0 +1,12 @@ +--- +title: Document.getSelection() +slug: Web/API/Document/getSelection +tags: + - Referencia + - Selección + - metodo +translation_of: Web/API/DocumentOrShadowRoot/getSelection +--- +

{{APIRef("DOM")}}

+ +

Este método funciona exactamente igual que {{domxref("Window.getSelection()")}}; devuelve un objeto {{domxref("Selection")}} que representa el texto que se ha seleccionado en el documento.

diff --git a/files/es/web/api/document/hasfocus/index.html b/files/es/web/api/document/hasfocus/index.html new file mode 100644 index 0000000000..a3f4a7ce9e --- /dev/null +++ b/files/es/web/api/document/hasfocus/index.html @@ -0,0 +1,23 @@ +--- +title: element.hasFocus +slug: Web/API/Document/hasFocus +tags: + - Referencia_DOM_de_Gecko +translation_of: Web/API/Document/hasFocus +--- +

{{ ApiRef() }}

+ +

Resumen

+ +

El atributo hasFocus devuelve true si el foco está en en algún sitio del documento activo. Este atributo es parte de la especificación HTML 5 actualmente en desarrollo.

+ +

Sintaxis

+ +
focused = element.hasFocus
+
+ +

Ejemplo

+ +

Especificación

+ +

Focus management

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

{{APIRef("DOM")}}

+ +

Devuelve el elemento {{HTMLElement("head")}} del documento actual. Si hay más de un elemento <head>, devuelve el primero de estos.

+ +

Sintaxis

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

Ejemplo

+ +
// en el 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 is de sólo lectura. Cualquier intento de asignar un valor a esta propiedad fallará silenciosamente o, en caso de que se encuentre en Modo estricto de ECMAScript en un navegador Gecko, lanzará un TypeError.

+ +

Compatibilidad con navegadores

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

Especificación

+ + diff --git a/files/es/web/api/document/height/index.html b/files/es/web/api/document/height/index.html new file mode 100644 index 0000000000..1bc2852c58 --- /dev/null +++ b/files/es/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}}
+ +
+

Note: Comenzando en {{Gecko("6.0")}}, document.height no es soportada. En lugar usar document.body.clientHeight. Ver {{domxref("element.clientHeight")}}.

+
+ +

Summary

+ +

Devuelve la altura del objeto {{domxref("document")}} . En la mayoría de los casos, esto equivale al elemento {{HTMLElement("body")}}  del documento actual.

+ +

Syntax

+ +
height_value = document.height
+
+ +

Example

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

Alternatives

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

Specification

+ +

HTML5

+ +

See also

+ + diff --git a/files/es/web/api/document/hidden/index.html b/files/es/web/api/document/hidden/index.html new file mode 100644 index 0000000000..e90970233b --- /dev/null +++ b/files/es/web/api/document/hidden/index.html @@ -0,0 +1,43 @@ +--- +title: Document.hidden +slug: Web/API/Document/hidden +translation_of: Web/API/Document/hidden +--- +

{{ ApiRef("DOM") }}

+ +

El  Document.hidden Es una propiedad solo de lectura, retorna un valor Booleano que indica si la pagina esta conciderada oculta o no.

+ +

Sintaxis

+ +
var boolean = document.hidden
+ +

Ejemplo

+ +
document.addEventListener("visibilitychange", function() {
+  console.log( document.hidden );
+  // Modify behavior...
+});
+
+ +

Especificaciones

+ + + + + + + + + + + + + + +
EspecificacionEstadoComentario
{{SpecName('Page Visibility API','#dom-document-hidden', 'Document.hidden')}}{{Spec2('Page Visibility API')}}definicion inicial
+ +

Compatibilidad con Navegadores

+ + + +

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

diff --git a/files/es/web/api/document/importnode/index.html b/files/es/web/api/document/importnode/index.html new file mode 100644 index 0000000000..ea34cd33be --- /dev/null +++ b/files/es/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")}}

+ +

Crea una copia de un nodo desde un documento externo para ser insertado en el documento actual.

+ +

Sintaxis

+ +
var node = document.importNode(externalNode, deep);
+
+ +
+
node
+
El nuevo nodo importado al documento actual. El parentNode del nuevo nodo es null, ya que aun no ha sido insertado en el arbol del documento.
+
externalNode
+
El nodo externo a ser importado
+
deep
+
Un booleano que indica si los descendientes del nodo deben ser importados también.
+
+ +
+

Nota: En la especificación DOM4 (tal y como se ha implementado en Gecko 13.0 {{geckoRelease(13)}}), deep es un argumento opcional. En el caso de ser omitido, adopta el valor de true, por lo que se hace una deep copy por defecto. Para realizar una copia superficial (shallow copy), deep debe ser false.

+ +

Este comportamiento ha cambiado en la ultima especificación, por lo que si se omite el parámetro deep, éste adopta el valor false. Aunque aún es opcional, debería ser siempre provisto por razones de compatibilidad. Con Gecko 28.0 {{geckoRelease(28)}}, la consola advertia a los desarrolladores de no omitir el argumento. Empezando con Gecko 29.0 {{geckoRelease(29)}}), se realiza una copia superficial (shallow copy) por defecto.

+
+ +

Ejemplo

+ +
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

+ +

El nodo original no se borra del documento. El nodo importado es un clon del 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.

+ +

 

+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + +
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
+ +

Compatibilidad navegadores

+ +
+ + +

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

+
+ +

See also

+ + diff --git a/files/es/web/api/document/index.html b/files/es/web/api/document/index.html new file mode 100644 index 0000000000..5b72f5850e --- /dev/null +++ b/files/es/web/api/document/index.html @@ -0,0 +1,390 @@ +--- +title: Documento +slug: Web/API/Document +tags: + - páginas_a_traducir +translation_of: Web/API/Document +--- +
{{ ApiRef }}
+ +
 
+ +

La interfaz Document representa cualquer página web cargada en el navegador y sirve como punto de entrada al contenido de la página (El árbol DOM). El DOM incluye elementos como {{HTMLElement("body")}} y {{HTMLElement("table")}}), entre muchos otros, y proporciona funcionalidad que es global al documento, como obtener la URL de la página y crear nuevos elementos en el documento.

+ +

{{inheritanceDiagram}}

+ +

La interfaz Document describe los métodos y propiedade comunes para cualquier clase de documento. Dependiento del tipo de documento (ej. HTML, XML, SVG, …), hay disponible una API más extensa: los documentos HTML, que se sirven con el tipo de contenido text/html, también implementan la interfaz {{domxref("HTMLDocument")}}, mientras que los documentos XML y SVG implementan la interfaz {{domxref("XMLDocument")}}.

+ +

Propiedades

+ +
+

Nota: La interfaz Document también hereda de las interfaces {{domxref("Node")}} y {{domxref("EventTarget")}}.

+
+ +
+
{{domxref("Document.all")}} {{Deprecated_inline}} {{non-standard_inline}}
+
Da acceso a todos los elementos del documento. Es una interfaz no estándar y no se debería utilizar.
+
{{domxref("Document.async")}} {{Deprecated_inline}}
+
Se utiliza con {{domxref("document.load")}} para indicar una petición asíncrona.
+
{{domxref("Document.characterSet")}} {{readonlyinline}}
+
Devuelve el juego de caracteres que utiliza el documento.
+
{{domxref("Document.charset")}} {{readonlyinline}} {{Deprecated_inline}}
+
Es un alias de {{domxref("Document.characterSet")}}. Utilice esta propiedad en su lugar.
+
{{domxref("Document.compatMode")}} {{experimental_inline}}
+
Indicates whether the document is rendered in Quirks or Strict mode.
+
{{domxref("Document.contentType")}} {{experimental_inline}}
+
Returns the Content-Type from the MIME Header of the current document.
+
{{domxref("Document.doctype")}}
+
Returns the Document Type Definition (DTD) of the current document.
+
{{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/es/web/api/document/keydown_event/index.html b/files/es/web/api/document/keydown_event/index.html new file mode 100644 index 0000000000..57dc4336a5 --- /dev/null +++ b/files/es/web/api/document/keydown_event/index.html @@ -0,0 +1,178 @@ +--- +title: keydown +slug: Web/API/Document/keydown_event +tags: + - Evento + - keydown +translation_of: Web/API/Document/keydown_event +--- +

El evento keydown se produce cuando se presiona una tecla.

+ +

A diferencia del evento keypress, el evento keydown es producido por todas las teclas, independientemente de si estas son caracteres o no.

+ +

Información general

+ +
+
Especificación
+
DOM L3
+
Interfaz
+
KeyboardEvent
+
Burbuja
+
Si
+
Cancelable
+
Si
+
Objetivo
+
Document, Element
+
Acción
+
Varía: evento keypress; lanza el sistema de composición de texto; eventos blur y focus; DOMActivate evento; otro evento
+
+ +

Propiedades

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
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.
+ +

preventDefault() del evento keydown

+ +

Empezando desde Gecko 25, una llamada a preventDefault() del evento keydown impide la emisión del consiguiente evento keypress. Este es un comportamiento válido para la especificación D3E y otros navegadores importantes que se comportan de esta misma forma. Por otro lado, Gecko 24 y anteriores emiten el evento keypress aunque se haya llamado a preventDefault() del evento keydown predecesor. Aunque el atributo defaultPrevented del evento keypress sea true en este caso.

+ +

Eventos relacionados

+ + + +

Ejemplo

+ +
<!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/es/web/api/document/keyup_event/index.html b/files/es/web/api/document/keyup_event/index.html new file mode 100644 index 0000000000..350629e9ab --- /dev/null +++ b/files/es/web/api/document/keyup_event/index.html @@ -0,0 +1,149 @@ +--- +title: Tecla Arriba +slug: Web/API/Document/keyup_event +translation_of: Web/API/Document/keyup_event +--- +

El evento es iniciado cuando la tecla es soltada.

+ +

Información General

+ +
+
Specification
+
DOM L3
+
Interface
+
KeyboardEvent
+
Bubbles
+
Si
+
Cancelable
+
Si
+
Target
+
Document, Element
+
Default Action
+
Ninguna
+
+ +

Propiedades

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
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/es/web/api/document/pointerlockelement/index.html b/files/es/web/api/document/pointerlockelement/index.html new file mode 100644 index 0000000000..cc5d490e5c --- /dev/null +++ b/files/es/web/api/document/pointerlockelement/index.html @@ -0,0 +1,105 @@ +--- +title: Document.pointerLockElement +slug: Web/API/Document/pointerLockElement +translation_of: Web/API/DocumentOrShadowRoot/pointerLockElement +--- +
{{APIRef("DOM")}}
+ +

La propiedad pointerLockElement conserva el elemento adquirido, para el evento del mouse, mientras el bloqueo se encuentre activo .  Es null si el bloqueo se encuentra en estado pendiente para bloqueo, o si el bloqueo se ha liberado, es decir ya no se encuentra en estado bloqueado, o si el elemento bloqueado se encuentra en otro documento.

+ +

Sintaxis

+ +
var elemento = document.pointerLockElement;
+
+ +

Valor retornado

+ +

Un {{domxref("Element")}} o null.

+ +

Especificaciones

+ + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName('Bloquear puntero','l#extension-to-the-document-interface','Document')}}{{Spec2('Pointer lock')}}Extiende de la interfaz Document
+ +

Compatibilidad del Navegador

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Soporte Básico{{ CompatVersionUnknown() }} {{property_prefix("webkit")}}{{CompatVersionUnknown}}{{ CompatVersionUnknown() }} {{property_prefix("moz")}}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
Soporte sin prefijar{{ CompatVersionUnknown() }}{{CompatUnknown}}{{CompatGeckoDesktop(50)}}   
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Soporte Básico{{ CompatUnknown() }}{{CompatVersionUnknown}}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

Véase también:

+ + diff --git a/files/es/web/api/document/queryselector/index.html b/files/es/web/api/document/queryselector/index.html new file mode 100644 index 0000000000..b442ba5bbb --- /dev/null +++ b/files/es/web/api/document/queryselector/index.html @@ -0,0 +1,136 @@ +--- +title: Document.querySelector() +slug: Web/API/Document/querySelector +tags: + - API + - Consulta + - DOM + - Referencias(2) + - Referências + - Selectores + - metodo +translation_of: Web/API/Document/querySelector +--- +
{{ ApiRef("DOM") }}
+ +
Devuelve el primer elemento del documento (utilizando un recorrido primero en profundidad pre ordenado de los nodos del documento) que coincida con el grupo especificado de selectores.
+ +
 
+ +

Sintaxis

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

Donde:

+ + + +

Ejemplo

+ +

En este ejemplo, obtendremos el primer elemento del documento con la clase "miClase":

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

Ejemplo más útil

+ +

Los Selectores pueden ser muy útiles como se demostrará en el siguiente ejemplo. Aquí, será retornado el primer elemento <input name="login" /> dentro de <div class="user-panel main">.

+ +
var el = document.querySelector("div.user-panel.main input[name='login']");
+ +

Notas

+ + + +
<div id="foo\bar"></div>
+<div id="foo:bar"></div>
+
+<script>
+  console.log('#foo\bar');               // "#fooar"
+  document.querySelector('#foo\bar');    // No coincide con nada
+
+  console.log('#foo\\bar');              // "#foo\bar"
+  console.log('#foo\\\\bar');            // "#foo\\bar"
+  document.querySelector('#foo\\\\bar'); // Coincide con el primer div
+
+  document.querySelector('#foo:bar');    // No coincide con nada
+  document.querySelector('#foo\\:bar');  // Coincide con el segundo div
+</script>
+
+ +

Compatibilidad en los navegadores

+ +
+ + + + + + + + + + + + + + + + + + + +
PlataformaChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Soporte Basico13.5 (1.9.1)
+ {{bug(416317)}}
8103.2 (525.3)
+ {{Webkitbug("16587")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
PlataformaAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Soporte Basico2.1Si910.03.2
+
+ +

Especificaciones

+ + + +

Vea también

+ + diff --git a/files/es/web/api/document/queryselectorall/index.html b/files/es/web/api/document/queryselectorall/index.html new file mode 100644 index 0000000000..7f041b6e84 --- /dev/null +++ b/files/es/web/api/document/queryselectorall/index.html @@ -0,0 +1,179 @@ +--- +title: Document.querySelectorAll() +slug: Web/API/Document/querySelectorAll +tags: + - API + - Buscando Elementos + - DOM + - Document + - Encontrando Elementos + - Localizando Elementos + - Métodos + - Referencia + - Seleccionando Elementos + - Selectores + - Selectores CSS + - querySelectorAll +translation_of: Web/API/Document/querySelectorAll +--- +
{{ ApiRef("DOM") }}
+ +

El método querySelectorAll() de un {{domxref("Element")}} devuelve una {{domxref("NodeList")}} estática (no viva) que representa una lista de elementos del documento que coinciden con el grupo de selectores indicados.

+ +
+

Nota: Esto método se implementa en base al método {{domxref("ParentNode.querySelectorAll", "querySelectorAll()")}} del mixin {{domxref("ParentNode")}}.

+
+ +

Sintaxis

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

Parámetros

+ +
+
selectors
+
Un {{domxref("DOMString")}} que contiene uno o más selectores para buscar coincidencias. Esta cadena de texto debe ser una cadena CSS selector válida; si no lo es, se lanzará una excepción SyntaxError. Vea Locating DOM elements using selectors para más información acerca de utilizar selectores para identificar elementos. Se pueden especificar varios selectores separándolos utilizando comas.
+
+ +
+

Nota: Los caracteres que no son parte de la sintaxis estándar de CSS deben ser escapados utilizando el caracter de barra invertida. Dado que JavaScript también utiliza el escapado por retroceso, se debe tener especial cuidado al escribir cadenas de texto literales utilizando estos caracteres. Vea {{anch("Escapando caracteres especiales")}} para más información.

+
+ +

Valor devuelto

+ +

Una {{domxref("NodeList")}} no viva que contenga un objeto {{domxref("Element")}} para cada elemento que coincida con al menos uno de los selectores especificados o una {{domxref("NodeList")}} vacía en caso de que no haya coincidencias.

+ +
+

Nota: Si los selectores indicados incluyen un pseudo-elemento CSS, la lista devuelta siempre estará vacía.

+
+ +

Excepciones

+ +
+
SyntaxError
+
La sintaxis de la cadena de texto selectors no es válida.
+
+ +

Ejemplos

+ +

Obteniendo una lista de coincidencias

+ +

Para obtener una {{domxref("NodeList")}} de todos los elementos {{HTMLElement("p")}} en el documento:

+ +
var matches = document.querySelectorAll('p');
+ +

Este ejemplo devuelve una lista de todos los elementos {{HTMLElement("div")}} del documento con una clase "nota" o "alerta":

+ +
var matches = document.querySelectorAll('div.nota, div.alerta');
+
+ +

Aquí, se obtiene una lista de elementos <p> cuyo elemento padre inmediato es un {{domxref("div")}} con la clase "highlighted" y que está ubicado dentro de un contenedor cuyo ID es "test".

+ +
var container = document.querySelector('#test');
+var matches = container.querySelectorAll('div.highlighted > p');
+ +

Este ejemplo usa un selector de atributos para devolver una lista de elementos {{domxref("iframe")}} en el documento que contienen un atributo llamado "data-src":

+ +
var matches = document.querySelectorAll('iframe[data-src]');
+ +

Aquí, un selector de atributo se utiliza para devolver una lista de los elementos de una lista cuyo ID es "userlist" que tiene un atributo "data-active" cuyo valor es "1":

+ +
var container = document.querySelector('#userlist');
+var matches = container.querySelectorAll('li[data-active="1"]');
+ +

Accediendo a las coincidencias

+ +

Una vez que se devuelve la {{domxref("NodeList")}} de los elementos que coinciden, se puede examinar como cualquier array. Si el array está vacío (lo que significa que su propiedad length es 0), entonces es que no se encontraron coincidencias.

+ +

En cualquier caso, se puede simplemente utilizar la notación estándar de los arrays para acceder al contenido de la lista. Se puede usar cualquier sentencia de iteración, como por ejemplo:

+ +
var highlightedItems = userList.querySelectorAll('.highlighted');
+
+highlightedItems.forEach(function(userItem) {
+  deleteUser(userItem);
+});
+ +

Notas de usuario

+ +

querySelectorAll() se comporta de forma diferente que la mayoría de librerías DOM de JavaScript, que pueden llevar a resultados inesperados.

+ +

HTML

+ +

Considere este HTML, con sus tres bloques anidados {{HTMLElement("div")}}.

+ +
<div class="outer">
+  <div class="select">
+    <div class="inner">
+    </div>
+  </div>
+</div>
+ +

JavaScript

+ +
var select = document.querySelector('.select');
+var inner = select.querySelectorAll('.outer .inner');
+inner.length; // 1, not 0!
+
+ +

En este ejemplo, cuando se selecciona ".outer .inner" en el contexto el <div> con la clase "select", el elemento con la clase ".inner" todavía es encontrado, aun sabiendo que .outer no es descendiente del elemento base sobre el que se realiza la búsqueda (".select"). Por defecto, querySelectorAll() sólo verifica que el último elemento en el selector se encuentra dentro del rango de búsqueda.

+ +

La pseudo-clase {{cssxref(":scope")}} recupera el comportamiento esperado, encontrando coincidencias sólo en selectores descendientes del elemento base:

+ +
var select = document.querySelector('.select');
+var inner = select.querySelectorAll(':scope .outer .inner');
+inner.length; // 0
+
+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName("DOM WHATWG", "#dom-parentnode-queryselectorall", "ParentNode.querySelectorAll()")}}{{Spec2("DOM WHATWG")}}Estándar vivo
{{SpecName("Selectors API Level 2", "#dom-parentnode-queryselectorall", "ParentNode.querySelectorAll()")}}{{Spec2("Selectors API Level 2")}}Sin cambios
{{SpecName("DOM4", "#dom-parentnode-queryselectorall", "ParentNode.querySelectorAll()")}}{{Spec2("DOM4")}}Definición inicial
{{SpecName("Selectors API Level 1", "#interface-definitions", "document.querySelector()")}}{{Spec2("Selectors API Level 1")}}Definición original
+ +

Compatibilidad en navegadores

+ +
+ + +

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

+
+ +

Ver también

+ + diff --git a/files/es/web/api/document/readystate/index.html b/files/es/web/api/document/readystate/index.html new file mode 100644 index 0000000000..7e5a24c5d8 --- /dev/null +++ b/files/es/web/api/document/readystate/index.html @@ -0,0 +1,104 @@ +--- +title: Document.readyState +slug: Web/API/Document/readyState +translation_of: Web/API/Document/readyState +--- +
{{APIRef("DOM")}} {{ gecko_minversion_header("1.9.2") }}
+ +

Resumen

+ +

La propiedad Document.readyState de un {{ domxref("document") }} describe el estado de carga del documento.

+ +

Valores

+ +

El readyState de un documento puede tener uno de los siguientes valores:

+ +
+
loading
+
El {{ domxref("document") }} todavía esta cargando.
+
interactive
+
El documento ha terminado de cargar y ha sido analizado pero  los sub-recursos como imágenes, estilos y frames aún siguen cargando. El estado indica que el evento {{event("DOMContentLoaded")}} ha sido disparado.
+
complete
+
El documento y todos los sub-recursos han cargado completamente. El estado indica que el evento {{event("load")}} ha sido disparado.
+
+ +

Cuando el valor de esta propiedad cambia, un evento {{event("readystatechange")}} se dispara en el objecto {{ domxref("document") }}.

+ +

Sintaxis

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

Ejemplos

+ +

Diferentes estados del readyState

+ +
switch (document.readyState) {
+  case "loading":
+    // The document is still loading.
+    break;
+  case "interactive":
+    // The document has finished loading. We can now access the DOM elements.
+    var span = document.createElement("span");
+    span.textContent = "A <span> element.";
+    document.body.appendChild(span);
+    break;
+  case "complete":
+    // The page is fully loaded.
+    console.log("The first CSS rule is: " + document.styleSheets[0].cssRules[0].cssText);
+    break;
+}
+
+ +

readystatechange como alternativa al evento DOMContentLoaded

+ +
// alternative to DOMContentLoaded event
+document.onreadystatechange = function () {
+  if (document.readyState == "interactive") {
+    initApplication();
+  }
+}
+ +

readystatechange como alternativa al evento load

+ +
// alternative to load event
+document.onreadystatechange = function () {
+  if (document.readyState == "complete") {
+    initApplication();
+  }
+}
+ +

Especificación

+ + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName("HTML WHATWG", "#current-document-readiness", "Document readiness")}}{{Spec2('HTML WHATWG')}} 
{{SpecName("HTML5.1", "#current-document-readiness", "Document readiness")}}{{Spec2('HTML5.1')}} 
{{SpecName("HTML5 W3C", "#current-document-readiness", "Document readiness")}}{{Spec2('HTML5 W3C')}}Especificación inicial.
+ +

Ver también

+ + diff --git a/files/es/web/api/document/registerelement/index.html b/files/es/web/api/document/registerelement/index.html new file mode 100644 index 0000000000..504cf8314b --- /dev/null +++ b/files/es/web/api/document/registerelement/index.html @@ -0,0 +1,115 @@ +--- +title: Document.registerElement() +slug: Web/API/Document/registerElement +translation_of: Web/API/Document/registerElement +--- +

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

+ +

El Document.registerElement() registra un nuevo elemento personalizado en el navegador y devuelve un constructor para el nuevo elemento.

+ +
+

Nota: Esta es una tecnología experimental. El navegador que utilice debe ser compatible con Web Components. Ver Web Components habilitados en Firefox.

+
+ +

Sintaxis

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

Parámetros

+ +
+
tag-name
+
El nombre del elemento personalizado. El nombre debe contener un guión (-), por ejemplo my-tag.
+
options {{optional_inline}}
+
Un objeto que da nombre al prototipo que sirve de base para el elemento personalizado, y una etiqueta existente para extender. Ambos son opcionales.
+
+ +

Ejemplo

+ +

Aquí hay un ejemplo muy simple:

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

Ahora el nuevo tag se ha registrado en el navegador. La variable MyTag contiene un constructor que lo puedes usar para crear un elemento my-tag  en el documento de la siguiente manera:

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

Esto inserta un elemento my-tag vacío que será visible si utiliza las herramientas de desarrollo del navegador. No será visible si usa la capacidad de ver el código fuente del navegador. Y no será visible en el navegador a menos que agregue algún contenido para la etiqueta. Esta es la manera de agregar contenido a la nueva etiqueta:

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

Especificaciones

+ + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName('Custom Elements')}}{{Spec2('Custom Elements')}}Definición inicial
+ +

Compatibilidad del navegador

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support3531 (behind a flag){{CompatNo}}25{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support4.4.431 (behind a flag){{CompatNo}}25{{CompatNo}}
+
+ +

Ver también

+ + diff --git a/files/es/web/api/document/scripts/index.html b/files/es/web/api/document/scripts/index.html new file mode 100644 index 0000000000..254df25276 --- /dev/null +++ b/files/es/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")}}
+ +

Devuelve una lista de elementos {{HTMLElement("script")}} ubicados en el documento. El objeto devuelto es una colección {{domxref("HTMLCollection")}}.

+ +

Sintáxis

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

El objeto scriptList devuelto es una {{domxref("HTMLCollection")}}. Se puede utilizar como un array corriente para acceder a sus elementos.

+ +

Ejemplo

+ +

Este ejemplo busca demostrar la existencia de objetos {{HTMLElement("script")}} en el documento.

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

Compatibilidad de navegadores

+ +
{{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}}
+
+ +

 

+ +

Especificaciones

+ + diff --git a/files/es/web/api/document/scroll_event/index.html b/files/es/web/api/document/scroll_event/index.html new file mode 100644 index 0000000000..944d539834 --- /dev/null +++ b/files/es/web/api/document/scroll_event/index.html @@ -0,0 +1,104 @@ +--- +title: scroll +slug: Web/API/Document/scroll_event +translation_of: Web/API/Document/scroll_event +--- +

El evento scroll se produce cuando la vista del documento o un elemento es deslizado.

+ +

Información General

+ +
+
Especificación
+
DOM L3, CSSOM View
+
Interfaz
+
UIEvent
+
Bubbles
+
No en elementos, pero burbujea a la vista default cuando se ejecuta en el documento
+
Cancelable
+
No
+
Objetivo
+
defaultView, Document, Element
+
Acción por defecto
+
Ninguna
+
+
+ +

Propiedades

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
target {{readonlyInline}}EventTargetEl objetivo de evento (el objetivo superior en el árbol DOM).
type {{readonlyInline}}DOMStringEl tipo de evento.
bubbles {{readonlyInline}}BooleanSi el evento burbujea o no.
cancelable {{readonlyInline}}BooleanSi el evento puede ser cancelado o no.
view {{readonlyInline}}WindowProxydocument.defaultView (window de el documento)
detail {{readonlyInline}}long (float)0.
+ +

Ejemplo

+ +

Dado que los eventos scroll pueden ejecutarse a un ritmo elevado, el event handler no debería ejecutar operaciones computacionalmente costosas como modificaciones en el DOM. En cambio, se recomienda acelerar el evento utilizando requestAnimationFrame, setTimeout or customEvent, de este modo:

+ +

Optimización de Scroll con window.requestAnimationFrame

+ +
// Referencia: http://www.html5rocks.com/en/tutorials/speed/animations/
+
+var last_known_scroll_position = 0;
+var ticking = false;
+
+function doSomething(scroll_pos) {
+  // Hacer algo con la posición del scroll
+}
+
+window.addEventListener('scroll', function(e) {
+  last_known_scroll_position = window.scrollY;
+  if (!ticking) {
+    window.requestAnimationFrame(function() {
+      doSomething(last_known_scroll_position);
+      ticking = false;
+    });
+  }
+  ticking = true;
+});
+ + + +

Más ejemplos se pueden ver en el evento resize.

+ +

Compatibilidad en navegadores

+ +

iOS UIWebView

+ +

En iOS UIWebViews, los eventos scroll no se ejecutan mientras el escroleo/deslizamiento se lleva a cabo; solo son ejecutados cuando el deslizamiento terminó. Ver Bootstrap issue #16202. Safari y WKWebViews no se ven afectados por este bug.

diff --git a/files/es/web/api/document/stylesheets/index.html b/files/es/web/api/document/stylesheets/index.html new file mode 100644 index 0000000000..0cc8e47181 --- /dev/null +++ b/files/es/web/api/document/stylesheets/index.html @@ -0,0 +1,21 @@ +--- +title: Document.styleSheets +slug: Web/API/Document/styleSheets +translation_of: Web/API/DocumentOrShadowRoot/styleSheets +--- +

{{ ApiRef() }}

+

Resumen

+

Devuelve una lista de objetos de tipo stylesheet para las hojas de estilo que están específicamente enlazadas o contenidas en el documento.

+

Propiedades

+

styleSheetList.length - devuelve el número de objetos de tipo stylesheet contenidos en el objeto.

+

Sintaxis

+
styleSheetList = document.styleSheets
+
+

El objeto devuelto es del tipo StyleSheetList.

+

Es una colección ordenada de objetos de tipo stylesheet. styleSheetList.item(index) o simplemente styleSheetList{{ mediawiki.external(' + + index + ') }} devuelve un único objeto de tipo stylesheet con el índice especificado (el índice es de origen 0).

+

Especificación

+

DOM Level 2 Style: styleSheets

+

{{ languages( { "ja": "ja/DOM/document.styleSheets", "pl": "pl/DOM/document.styleSheets" } ) }}

diff --git a/files/es/web/api/document/url/index.html b/files/es/web/api/document/url/index.html new file mode 100644 index 0000000000..eec4361827 --- /dev/null +++ b/files/es/web/api/document/url/index.html @@ -0,0 +1,71 @@ +--- +title: document.URL +slug: Web/API/Document/URL +tags: + - API + - Documento + - HTML DOM + - Propiedad + - Referencia +translation_of: Web/API/Document/URL +--- +
{{APIRef("DOM")}}
+ +

La propiedad de sólo lectura URL de la interfaz {{domxref("Document")}} devuelve la ubicación del documento como una cadena de texto.

+ +

Sintaxis

+ +
var string = document.URL
+ +

Ejemplo

+ +

JavaScript

+ +
document.getElementById("url").textContent = document.URL;
+ +

HTML

+ +
<p id="urlText">
+  URL:<br/>
+  <span id="url">La URL va aquí</span>
+</p>
+ +

Resultado

+ +

{{EmbedLiveSample("Example", "100%", 100)}}

+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName("DOM WHATWG", "#dom-document-url", "Document.URL")}}{{Spec2("DOM WHATWG")}}Define que la propiedad es una {{domxref("USVString")}} en lugar de un {{domxref("DOMString")}}.
{{SpecName("DOM1", "level-one-html.html#attribute-URL", "Document.URL")}}{{Spec2("DOM1")}}Definición inicial
+ +

Compatibilidad con navegadores

+ +
+

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

+
+ +

Ver también

+ + diff --git a/files/es/web/api/document/write/index.html b/files/es/web/api/document/write/index.html new file mode 100644 index 0000000000..f07bd5c9a9 --- /dev/null +++ b/files/es/web/api/document/write/index.html @@ -0,0 +1,76 @@ +--- +title: Document.write() +slug: Web/API/Document/write +tags: + - API + - DOM + - Documentación + - Referencia + - metodo +translation_of: Web/API/Document/write +--- +
{{ ApiRef("DOM") }}
+ +


+ Escribe una cadena de texto dentro del hilo de un document abierto por document.open().

+ +
Nota: dado que document.write escribe directo al hilo (stream) de un documento, la llamada a document.write en un documento ya cargado automáticamente ejecuta document.open, lo cual limpiará todo el contenido del documento en cuestión.
+ +

Sintaxis

+ +
document.write(texto);
+
+ +

texto es una cadena de texto que contiene el texto a ser impreso en el documento.

+ +

Example

+ +
<html>
+
+<head>
+  <title>Ejemplo de write</title>
+
+  <script>
+    function nuevoContenido() {
+      alert("carga el contenido nuevo");
+      document.open();
+      document.write("<h1>Quita el contenido viejo - Agrega el contenido nuevo!</h1>");
+      document.close();
+    }
+  </script>
+</head>
+
+<body onload="nuevoContenido();">
+  <p>Algo de contenido original del documento</p>
+</body>
+
+</html>
+ +

Notas

+ +

Escribir a un documento que ya tiene contenido cargado previamente sin llamar a document.open(), automáticamente hará una llamada a document.open(). Después de haber finalizado la escritura del documento, es recomendable llamar a document.close(), para informar al navegador que la carga de la página ya ha terminado. El texto que escribas allí es convertido a la estructura tipificada de HTML dentro del modelo estructural del documento. En el ejemplo de más arriba, el elemento h1 se convierte en un nodo dentro del documento.

+ +

Si la llamada a document.write() se ejecuta dentro de una etiqueta <script> incluído en el HTML, entonces la llamada a document.open() nunca ocurrirá. Por ejemplo:

+ +
<script>
+  document.write("<h1>Título Principal</h1>")
+</script>
+
+ +
Nota: document.write y document.writeln no funcionan dentro de un documento XHTML (obtendrás un mensaje de error que dice "Operación no soportada" ("Operation is not supported") [NS_ERROR_DOM_NOT_SUPPORTED_ERR] en la consola). Esto sucede cuando abrimos un archivo local de extensión .xhtml o para cualquier document servido con un MIME del tipo application/xhtml+xml. Hay más información disponible en W3C XHTML FAQ.
+ +
Nota: document.write en scripts de modo diferido o asyncrónico serán ignorados, y recibirás un mensaje de error en la consola del tipo "Una llamada a document.write() desde un script cargado asincrónicamente fue ignorado" ("A call to document.write() from an asynchronously-loaded external script was ignored").
+ +

Especificaciones

+ + + +

También puedes ver

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

{{ ApiRef("DOM") }}

+ +

Escribe una cadena de texto en el documento, seguida de una nueva línea.

+ +
+

Nota: dado que document.writeln (al igual que document.write) escribe directo al hilo (stream) de un documento, la llamada a document.write en un documento ya cargado automáticamente ejecuta document.open, lo cual limpiará todo el contenido del documento en cuestión.

+
+ +

Sintaxis

+ +
document.writeln(línea);
+
+ +

Parámetros

+ + + +

Ejemplo

+ +
document.writeln("<p>¡Hola mundo!</p>");
+
+ +

Notas

+ +

document.writeln actúa igual que document.write exepto que agrega un carácter de nueva línea (\n) al final del texto a escribir.

+ +
Nota: document.write y document.writeln no funcionan dentro de un documento XHTML (obtendrás un mensaje de error que dice "Operación no soportada" ("Operation is not supported") [NS_ERROR_DOM_NOT_SUPPORTED_ERR] en la consola). Esto sucede cuando abrimos un archivo local de extensión .xhtml o para cualquier document servido con un MIME del tipo application/xhtml+xml. Hay más información disponible en W3C XHTML FAQ.
+ +
Nota: document.writeln y document.write en scripts de modo diferido o asyncrónico serán ignorados, y recibirás un mensaje de error en la consola del tipo "Una llamada a document.write() desde un script cargado asincrónicamente fue ignorado" ("A call to document.write() from an asynchronously-loaded external script was ignored").
+ +

Especificación

+ +

writeln

-- cgit v1.2.3-54-g00ecf