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/node/appendchild/index.html | 113 +++++++ files/es/web/api/node/childnodes/index.html | 103 +++++++ files/es/web/api/node/clonenode/index.html | 91 ++++++ files/es/web/api/node/contains/index.html | 56 ++++ files/es/web/api/node/elementopadre/index.html | 46 +++ files/es/web/api/node/haschildnodes/index.html | 73 +++++ files/es/web/api/node/index.html | 371 +++++++++++++++++++++++ files/es/web/api/node/insertarantes/index.html | 172 +++++++++++ files/es/web/api/node/issamenode/index.html | 110 +++++++ files/es/web/api/node/lastchild/index.html | 65 ++++ files/es/web/api/node/namespaceuri/index.html | 145 +++++++++ files/es/web/api/node/nextsibling/index.html | 87 ++++++ files/es/web/api/node/nodename/index.html | 107 +++++++ files/es/web/api/node/nodetype/index.html | 95 ++++++ files/es/web/api/node/nodevalue/index.html | 86 ++++++ files/es/web/api/node/nodoprincipal/index.html | 33 ++ files/es/web/api/node/ownerdocument/index.html | 118 +++++++ files/es/web/api/node/parentnode/index.html | 105 +++++++ files/es/web/api/node/previoussibling/index.html | 63 ++++ files/es/web/api/node/removechild/index.html | 94 ++++++ files/es/web/api/node/replacechild/index.html | 73 +++++ files/es/web/api/node/textcontent/index.html | 98 ++++++ 22 files changed, 2304 insertions(+) create mode 100644 files/es/web/api/node/appendchild/index.html create mode 100644 files/es/web/api/node/childnodes/index.html create mode 100644 files/es/web/api/node/clonenode/index.html create mode 100644 files/es/web/api/node/contains/index.html create mode 100644 files/es/web/api/node/elementopadre/index.html create mode 100644 files/es/web/api/node/haschildnodes/index.html create mode 100644 files/es/web/api/node/index.html create mode 100644 files/es/web/api/node/insertarantes/index.html create mode 100644 files/es/web/api/node/issamenode/index.html create mode 100644 files/es/web/api/node/lastchild/index.html create mode 100644 files/es/web/api/node/namespaceuri/index.html create mode 100644 files/es/web/api/node/nextsibling/index.html create mode 100644 files/es/web/api/node/nodename/index.html create mode 100644 files/es/web/api/node/nodetype/index.html create mode 100644 files/es/web/api/node/nodevalue/index.html create mode 100644 files/es/web/api/node/nodoprincipal/index.html create mode 100644 files/es/web/api/node/ownerdocument/index.html create mode 100644 files/es/web/api/node/parentnode/index.html create mode 100644 files/es/web/api/node/previoussibling/index.html create mode 100644 files/es/web/api/node/removechild/index.html create mode 100644 files/es/web/api/node/replacechild/index.html create mode 100644 files/es/web/api/node/textcontent/index.html (limited to 'files/es/web/api/node') diff --git a/files/es/web/api/node/appendchild/index.html b/files/es/web/api/node/appendchild/index.html new file mode 100644 index 0000000000..a72eb7d6c3 --- /dev/null +++ b/files/es/web/api/node/appendchild/index.html @@ -0,0 +1,113 @@ +--- +title: Nodo appendChild +slug: Web/API/Node/appendChild +tags: + - API + - DOM + - Node + - Referencia + - metodo +translation_of: Web/API/Node/appendChild +--- +
{{APIRef("DOM")}}
+ +

Agrega un nuevo nodo al final de la lista de un elemento hijo de un elemento padre especificado.

+ +

Si el hijo(Child) es una referencia(hace referencia) hacia un nodo existente en el documento actual, este es quitado del padre actual para ser puesto en el nodo padre nuevo. La clave está en si el (Child) es una referencia a un nodo existente en el documento.

+ +
+

Nueva API disponible 
+ El método {{domxref("ParentNode.append()")}} soporta varios argumentos y cadenas para adjuntar.

+
+ +

Sintaxis

+ +
element.appendChild(aChild);
+ +

Parámetros

+ +
+
aChild
+
El nodo a adjuntar al nodo padre proporcionado (normalmente un elemento).
+
+ +

Valor de retorno

+ +

El valor devuelto es el hijo adjunto excepto cuando el hijo proporcionado es un {{domxref("DocumentFragment")}}, en cuyo caso el {{domxref("DocumentFragment")}} vacío es devuelto.

+ +

Notas

+ +

El encadenamiento podría no funcionar como se espera debido a que appendChild() devuelve un elemento hijo:

+ +
var aBlock = doc.createElement('block').appendChild(doc.createElement('b'));
+ +

Establece aBlock como <b></b> sólo, que no es probablemente lo que quieras.

+ +

Si el child hace una referencia a un nodo existente en el documento, el método appendChild se mueve de su posición actual a su nueva posición (ej. no existen requerimientos para eliminar el nodo desde su nodo padre antes de añadirlo a cualquier otro nodo).

+ +

Ésto significa también que el nodo no puede estar en dos puntos del documento de manera simultánea. Así que si el nodo ya contiene un padre, primero es eliminado, y después se añade a la nueva posición.

+ +

Se puede usar {{domxref("Node.cloneNode")}} para hacer una copia del nodo antes de añadirlo debajo de su nuevo elemento padre. (Nota: las copias echas con cloneNode no serán guardadas automáticamente en sincronía.)

+ +

Éste método no es permitido para mover nodos entre distintos documentos. Si se quiere añadir un nodo desde un documento diferente (por ejemplo para mostrar los resultados de una petición AJAX) se debe usar primero:
+ {{domxref("document.importNode")}}.

+ +

appendChild() Es uno de los métodos fundamentales de la programación web usando el DOM. El método appendChild() inserta un nuevo nodo dentro de la estructura DOM de un documento, y es la segunda parte del proceso central uno-dos, crear-y-añadir para construir páginas web a base de programación.

+ +

Ejemplo

+ +
// Crea un nuevo elemento párrafo, y lo agrega al final del cuerpo del documento
+var p = document.createElement("p");
+document.body.appendChild(p);
+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecifaciónEstadoComentario
{{SpecName('DOM WHATWG', '#dom-node-appendchild', 'Node.appendChild()')}}{{Spec2('DOM WHATWG')}}Sin cambio desde {{SpecName("DOM3 Core")}}.
{{SpecName('DOM3 Core', 'core.html#ID-184E7107', 'Node.appendChild()')}}{{Spec2('DOM3 Core')}}Sin cambio desde {{SpecName("DOM2 Core")}}.
{{SpecName('DOM2 Core', 'core.html#ID-184E7107', 'Node.appendChild()')}}{{Spec2('DOM2 Core')}}Sin cambio desde {{SpecName("DOM1")}}.
{{SpecName('DOM1', 'level-one-core.html#ID-184E7107', 'Node.appendChild()')}}{{Spec2('DOM1')}}Definición inicial.
+ +

Compatibilidad con navegadores

+ +
+ + +

{{Compat("api.Node.appendChild")}}

+
+ +

Ver también

+ + diff --git a/files/es/web/api/node/childnodes/index.html b/files/es/web/api/node/childnodes/index.html new file mode 100644 index 0000000000..567cd9fd08 --- /dev/null +++ b/files/es/web/api/node/childnodes/index.html @@ -0,0 +1,103 @@ +--- +title: Node.childNodes +slug: Web/API/Node/childNodes +tags: + - API + - DOM + - Propiedad + - Referencia + - Referência DOM +translation_of: Web/API/Node/childNodes +--- +
+
{{APIRef("DOM")}}
+
+ +

La propiedad de solo lectura Node.childNodes  devuelve una colección de hijos {{domxref("Node","nodes")}} del elemento dado donde el primer nodo hijo es asignado un índice 0.

+ +

Sintaxis

+ +
var nodeList = elementNodeReference.childNodes;
+
+ +

Ejemplos

+ +

Uso simple

+ +
// parg is an object reference to a <p> element
+
+// First check that the element has child nodes
+if (parg.hasChildNodes()) {
+  var children = parg.childNodes;
+
+  for (var i = 0; i < children.length; i++) {
+    // do something with each child as children[i]
+    // NOTE: List is live, adding or removing children will change the list
+  }
+}
+ +

Eliminar todos los hijos de un nodo

+ +
// This is one way to remove all children from a node
+// box is an object reference to an element
+
+while (box.firstChild) {
+    //The list is LIVE so it will re-index each call
+    box.removeChild(box.firstChild);
+}
+ +

Notas

+ +

Los items en una colección de nodos son objetos y no cadenas de caracteres. Para obtener los datos de los objetos del nodo, use sus propiedades (ej. elementNodeReference.childNodes[1].nodeName para obtener el nombre, etc.).

+ +

El objeto document contiene 2 hijos: la declaración del Doctype y el elemento raíz, generalmente referido como  documentElement. (En documentos (X)HTML  es el elemento HTML)

+ +

childNodes incluye todos los nodos hijos, incluidos los nodos no elementos, como nodos de tipo textos y comentarios. Para obtener una colección de solo elementos, use {{domxref("ParentNode.children")}}.

+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaciónEstadoComentarios
{{SpecName('DOM WHATWG', '#dom-node-childnodes', 'Node.childNodes')}}{{Spec2('DOM WHATWG')}}Sin cambios
{{SpecName('DOM3 Core', 'core.html#ID-1451460987', 'Node.childNodes')}}{{Spec2('DOM3 Core')}}Sin cambios
{{SpecName('DOM2 Core', 'core.html#ID-1451460987', 'Node.childNodes')}}{{Spec2('DOM2 Core')}}Sin cambios
{{SpecName('DOM1', 'level-one-core.html#ID-1451460987', 'Node.childNodes')}}{{Spec2('DOM1')}}Definición inicial
+ +

Compatibilidad con navegadores

+ +

{{Compat("api.Node.childNodes")}}

+ +

Vea también

+ + diff --git a/files/es/web/api/node/clonenode/index.html b/files/es/web/api/node/clonenode/index.html new file mode 100644 index 0000000000..0fb78af5dd --- /dev/null +++ b/files/es/web/api/node/clonenode/index.html @@ -0,0 +1,91 @@ +--- +title: Node.cloneNode() +slug: Web/API/Node/cloneNode +tags: + - API + - DOM + - Referencia + - Referência DOM + - metodo +translation_of: Web/API/Node/cloneNode +--- +
{{APIRef("DOM")}}
+ +

El método Node.cloneNode() devuelve un duplicado del nodo en el que este método fue llamado.

+ +

Sintaxis

+ +
var dupNode = node.cloneNode(deep);
+
+ +
+
node
+
El nodo que se desea clonar.
+
dupNode
+
El nuevo nodo que será un clon de node
+
deep {{optional_inline}}
+
true si los hijos del nodo también deben ser clonados, o false para clonar únicamente al nodo.
+
+ +
+

Nota: En la especificación DOM4 (como se implementó en Gecko 13.0 {{geckoRelease(13)}}), deep es un argumento opcional. Si éste se omite, el método actua como si el valor se estableciera en true, estableciendo el uso de la clonación profunda como el comportamiento por defecto. Para crear un clon superficial, deep debe establecerse en false.

+ +

Este comportamiento ha sido modificado en la última especificación, si es omitido, el método se comportará como si deep fuera false. Aunque sigue siendo opcional, usted siempre debería proporcionar el argumento deep tanto para la compatibilidad con las nuevas y anteriores especificaciones. Con Gecko 28.0 {{geckoRelease(28)}}),  la consola advierte a los desarrolladores a no omitir el argumento. Desde Gecko 29.0 {{geckoRelease(29)}}),  una copia superficial, es el comportamiento por defecto en lugar de una copia profunda.

+
+ +

Ejemplo

+ +
var p = document.getElementById("para1");
+var p_prime = p.cloneNode(true);
+
+ +

Notas

+ +

Al clonar un nodo se copian todos sus atributos y valores, incluyendo escuchadores intrínsecos (en–línea). No copia los escuchadores de evento añadidos utilizando addEventListener() o aquellos asignados a las propiedades de un elemento. (ej. node.onclick = fn). Además, para un elemento <canvas>, la imagen pintada no se copia.

+ +

El nodo duplicado devuelto por cloneNode() no formará parte del documento hasta que sea añadido a otro nodo que sea parte del documento utilizando {{domxref("Node.appendChild()")}} o un método similar. Tampoco tiene padre hasta que sea añadido a otro nodo.

+ +

Si deep se establece a false, los elementos hijos no se clonan. Tampoco se clona ningún texto que contenga el nodo, ya que está contenido en uno o más nodos {{domxref("Text")}}.

+ +

Si deep se evalúa a true, el subárbol completo (incluyendo texto que pueda estar en nodos {{domxref("Text")}} hijos) también se copian. En los nodos vacíos (por ejemplo, los elementos {{HTMLElement("img")}} y {{HTMLElement("input")}}) no importa si deep es true o false.

+ +
Advertencia: cloneNode() puede conducir a elementos con ID's duplicados en el documento.
+ +

Si el nodo original tiene un ID el elemento clonado se ubicará en el mismo documento, el ID del clon debería ser modificado para ser único. Los atributos name pueden necesitar ser modificados también, dependiendo de si se esperan nombres duplicados.

+ +

Para clonar un nodo con el fin de agregarlo a un domento distinto, utiliza {{domxref("Document.importNode()")}}.

+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName("DOM WHATWG", "#dom-node-clonenode", "Node.cloneNode()")}}{{Spec2("DOM WHATWG")}} 
{{SpecName("DOM3 Core", "core.html#ID-3A0ED0A4", "Node.cloneNode()")}}{{Spec2("DOM3 Core")}} 
{{SpecName("DOM2 Core", "core.html#ID-3A0ED0A4", "Node.cloneNode()")}}{{Spec2("DOM2 Core")}}Definición inicial
+ +

Compatibilidad en navegadores

+ +
+

{{Compat("api.Node.cloneNode")}}

+
diff --git a/files/es/web/api/node/contains/index.html b/files/es/web/api/node/contains/index.html new file mode 100644 index 0000000000..be0f8848d9 --- /dev/null +++ b/files/es/web/api/node/contains/index.html @@ -0,0 +1,56 @@ +--- +title: Node.contains() +slug: Web/API/Node/contains +tags: + - API + - DOM + - Nodo + - metodo +translation_of: Web/API/Node/contains +--- +
{{APIRef("DOM")}}
+ +

El método Node.contains() devuelve un valor {{jsxref("Boolean")}} indicando si un nodo es descendiente de un nodo dado o no, por ejemplo, el propio nodo, uno de sus hijos directos (({{domxref("Node.childNodes", "childNodes")}})), uno de los hijos directos de su nodo hijo, etc.

+ +

Sintaxis

+ +
node.contains( otroNodo )
+
+ +

Ejemplo

+ +

Esta función verifica si un un elemento esté en el cuerpo de la página. Como contains es inclusivo y determinar si el cuerpo se contiene a sí mismo no es la intención de  isInPage este caso explícitamente devuelve false.

+ +
function isInPage(node) {
+  return (node === document.body) ? false : document.body.contains(node);
+}
+ +

Especificaciones

+ + + + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName("DOM WHATWG", "#dom-node-contains", "Node.contains()")}}{{Spec2("DOM WHATWG")}}Definición inicial
+ +

Compatibilidad en navegadores

+ +

{{Compat("api.Node.contains")}}

+ +

Ver también

+ + diff --git a/files/es/web/api/node/elementopadre/index.html b/files/es/web/api/node/elementopadre/index.html new file mode 100644 index 0000000000..2a2e947a8d --- /dev/null +++ b/files/es/web/api/node/elementopadre/index.html @@ -0,0 +1,46 @@ +--- +title: Node.parentElement +slug: Web/API/Node/elementoPadre +tags: + - API + - DOM + - NecesitaCompatiblidadNavegador + - Nodo + - Propiedad +translation_of: Web/API/Node/parentElement +--- +
+
{{APIRef("DOM")}}
+
+ +

La propiedad de sólo lectura de Nodo.parentElement devuelve el nodo padre del DOM {{domxref("Element")}}, o null, si el nodo no tiene padre o si el padre no es un {{domxref("Element")}} DOM .

+ +

Sintaxis

+ +
elementoPadre = node.parentElement
+ +

El elementoPadre es el padre del nodo actual. Esto es siempre un objecto {{domxref("Element")}} DOM, o null.

+ +

Ejemplo

+ +
if (node.parentElement) {
+    node.parentElement.style.color = "red";
+}
+ +

Compatibilidad en navegadores

+ +

En algunos navegadores, la propiedad elementoPadre es solo definida en nodos que ellos mismos son {{domxref("Element")}}. En particular, esto no está definido en nodos de texto.

+ +

{{Compat("api.Node.parentElement")}}

+ +

Especificación

+ + + +

Ver también

+ + diff --git a/files/es/web/api/node/haschildnodes/index.html b/files/es/web/api/node/haschildnodes/index.html new file mode 100644 index 0000000000..b5b3bc58b2 --- /dev/null +++ b/files/es/web/api/node/haschildnodes/index.html @@ -0,0 +1,73 @@ +--- +title: Node.hasChildNodes() +slug: Web/API/Node/hasChildNodes +tags: + - API + - DOM + - Nodo + - metodo +translation_of: Web/API/Node/hasChildNodes +--- +
+
{{APIRef("DOM")}}
+
+ +

El método Node.hasChildNodes() devuelve un valor Boolean indicando si el {{domxref("Node")}} (nodo) actual tiene nodos hijos o no.

+ +

Sintaxis

+ +
resultado = node.hasChildNodes();
+ +
+
resultado
+
almacena el valor devuelto truefalse.
+
+ +

Ejemplos

+ +

El siguiente ejemplo elimina el primer nodo dentro del elemento con id "foo" si foo tiene nodos hijos.

+ +
var foo = document.getElementById("foo");
+if (foo.hasChildNodes()) {
+    // do something with 'foo.childNodes'
+}
+
+ +

Polyfill

+ +
;(function(prototype) {
+    prototype.hasChildNodes = prototype.hasChildNodes || function() {
+        return !!this.firstChild;
+    }
+})(Node.prototype);
+
+ +

Resumen

+ +

Hay varias maneras de determinar si el nodo tiene nodos hijos.

+ + + +

Especificación

+ + + +

Compatibilidad con navegadores

+ + + +

{{Compat("api.Node.hasChildNodes")}}

+ +

Ver también

+ + diff --git a/files/es/web/api/node/index.html b/files/es/web/api/node/index.html new file mode 100644 index 0000000000..6511274333 --- /dev/null +++ b/files/es/web/api/node/index.html @@ -0,0 +1,371 @@ +--- +title: Node +slug: Web/API/Node +tags: + - API + - DOM + - Interfaz + - Nodo + - Referencia +translation_of: Web/API/Node +--- +
{{APIRef("DOM")}}
+ +

Node es una interfaz en la cuál un número de objetos de tipo DOM API heredan. Esta interfaz permite que esos objetos sean tratados similarmente.

+ +

Las siguientes interfaces todas heredan de los metodos y propiedades de Node: {{domxref("Document")}}, {{domxref("Element")}}, {{domxref("CharacterData")}} (heredan el {{domxref("Text")}}, el {{domxref("Comment")}}, y {{domxref("CDATASection")}}), {{domxref("ProcessingInstruction")}}, {{domxref("DocumentFragment")}}, {{domxref("DocumentType")}}, {{domxref("Notation")}}, {{domxref("Entity")}}, {{domxref("EntityReference")}}

+ +

Estas interfaces pueden retornar null en casos particulares donde los métodos y las propiedades no son relevantes. Pueden retornar una excepción - por ejemplo cuando se agregan hijos a un tipo de node del cuál no puede existir hijos.

+ +

Propiedades

+ +

herendan propiedades de sus padres {{domxref("EventTarget")}}.[1]

+ +
+
{{domxref("Node.baseURI")}} {{readonlyInline}}
+
Retorna un {{domxref("DOMString")}} representando la base de la URL. El concepto de la base de la URL cambia de un lenguaje a otro;  en HTML, le corresponde al protocolo, el nombre del dominio y la estructura del directorio, eso es todo hasta el último '/'.
+
{{domxref("Node.baseURIObject")}} {{Non-standard_inline()}} {{ Fx_minversion_inline("3") }}
+
(Not available to web content.) The read-only {{ Interface("nsIURI") }} object representing the base URI for the element.
+
{{domxref("Node.childNodes")}} {{readonlyInline}}
+
Returns a live {{domxref("NodeList")}} containing all the children of this node. {{domxref("NodeList")}} being live means that if the children of the Node change, the {{domxref("NodeList")}} object is automatically updated.
+
{{domxref("Node.firstChild")}} {{readonlyInline}}
+
Returns a {{domxref("Node")}} representing the first direct child node of the node, or null if the node has no child.
+
{{domxref("Node.lastChild")}} {{readonlyInline}}
+
Returns a {{domxref("Node")}} representing the last direct child node of the node, or null if the node has no child.
+
{{domxref("Node.localName")}} {{obsolete_inline}}{{readonlyInline}}
+
Returns a {{domxref("DOMString")}} representing the local part of the qualified name of an element. In Firefox 3.5 and earlier, the property upper-cases the local name for HTML elements (but not XHTML elements). In later versions, this does not happen, so the property is in lower case for both HTML and XHTML. {{ gecko_minversion_inline("1.9.2") }}
+ Though recent specifications require localName to be defined on the {{domxref("Element")}} interface, Gecko-based browsers still implement it on the {{domxref("Node")}} interface.
+
{{domxref("Node.namespaceURI")}} {{obsolete_inline}}{{readonlyInline}}
+
The namespace URI of this node, or null if it is no namespace. In Firefox 3.5 and earlier, HTML elements are in no namespace. In later versions, HTML elements are in the http://www.w3.org/1999/xhtml namespace in both HTML and XML trees. {{ gecko_minversion_inline("1.9.2") }}
+ Though recent specifications require namespaceURI to be defined on the {{domxref("Element")}} interface, Gecko-based browsers still implement it on the {{domxref("Node")}} interface.
+
{{domxref("Node.nextSibling")}} {{readonlyInline}}
+
Returns a {{domxref("Node")}} representing the next node in the tree, or null if there isn't such node.
+
{{domxref("Node.nodeName")}} {{readonlyInline}}
+
Returns a {{domxref("DOMString")}} containing the name of the Node. The structure of the name will differ with the name type. E.g. An {{domxref("HTMLElement")}} will contain the name of the corresponding tag, like 'audio' for an {{domxref("HTMLAudioElement")}}, a {{domxref("Text")}} node will have the '#text' string, or a {{domxref("Document")}} node will have the '#document' string.
+
{{domxref("Node.nodePrincipal")}} {{Non-standard_inline()}}{{ Fx_minversion_inline("3") }}
+
A {{ Interface("nsIPrincipal") }} representing the node principal.
+
{{domxref("Node.nodeType")}}{{readonlyInline}}
+
Returns an unsigned short representing the type of the node. Possible values are: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameValue
ELEMENT_NODE1
ATTRIBUTE_NODE {{deprecated_inline()}}2
TEXT_NODE3
CDATA_SECTION_NODE {{deprecated_inline()}}4
ENTITY_REFERENCE_NODE {{deprecated_inline()}}5
ENTITY_NODE {{deprecated_inline()}}6
PROCESSING_INSTRUCTION_NODE7
COMMENT_NODE8
DOCUMENT_NODE9
DOCUMENT_TYPE_NODE10
DOCUMENT_FRAGMENT_NODE11
NOTATION_NODE {{deprecated_inline()}}12
+
+
{{domxref("Node.nodeValue")}}
+
Is a {{domxref("DOMString")}} representing the value of an object. For most Node type, this returns null and any set operation is ignored. For nodes of type TEXT_NODE ({{domxref("Text")}} objects), COMMENT_NODE ({{domxref("Comment")}} objects), and PROCESSING_INSTRUCTION_NODE ({{domxref("ProcessingInstruction")}} objects), the value corresponds to the text data contained in the object.
+
{{domxref("Node.ownerDocument")}} {{readonlyInline}}
+
Returns the {{domxref("Document")}} that this node belongs to. If no document is associated with it, returns null.
+
{{domxref("Node.parentNode")}} {{readonlyInline}}
+
Returns a {{domxref("Node")}} that is the parent of this node. If there is no such node, like if this node is the top of the tree or if doesn't participate in a tree, this property returns null.
+
{{domxref("Node.parentElement")}} {{readonlyInline}}
+
Returns an {{domxref("Element")}} that is the parent of this node. If the node has no parent, or if that parent is not an {{domxref("Element")}}, this property returns null.
+
{{domxref("Node.prefix")}} {{obsolete_inline}}{{readonlyInline}}
+
Is a {{domxref("DOMString")}} representing the namespace prefix of the node, or null if no prefix is specified.
+ Though recent specifications require prefix to be defined on the {{domxref("Element")}} interface, Gecko-based browsers still implement it on the {{domxref("Node")}} interface.
+
{{domxref("Node.previousSibling")}} {{readonlyInline}}
+
Returns a {{domxref("Node")}} representing the previous node in the tree, or null if there isn't such node.
+
{{domxref("Node.textContent")}}
+
Is a {{domxref("DOMString")}} representing the textual content of an element and all its descendants.
+
+ +

Methods

+ +

Inherits methods from its parents {{domxref("EventTarget")}}.[1]

+ +
+
{{domxref("Node.appendChild()")}}
+
Insert a {{domxref("Node")}} as the last child node of this element.
+
{{domxref("Node.cloneNode()")}}
+
Clone a {{domxref("Node")}}, and optionally, all of its contents. By default, it clones the content of the node.
+
{{domxref("Node.compareDocumentPosition()")}}
+
 
+
{{domxref("Node.contains()")}}
+
 
+
{{domxref("Node.getFeature()")}} {{obsolete_inline}}
+
...
+
{{domxref("Node.getUserData()")}} {{obsolete_inline}}
+
Allows a user to get some {{domxref("DOMUserData")}} from the node.
+
{{domxref("Node.hasAttributes()")}} {{obsolete_inline}}
+
Returns a {{domxref("Boolean")}} indicating if the element has any attributes, or not.
+
{{domxref("Node.hasChildNodes()")}}
+
Returns a {{domxref("Boolean")}} indicating if the element has any child nodes, or not.
+
{{domxref("Node.insertBefore()")}}
+
Inserts the first {{domxref("Node")}} given in a parameter immediately before the second, child of this element, {{domxref("Node")}}.
+
{{domxref("Node.isDefaultNamespace()")}}
+
 
+
{{domxref("Node.isEqualNode()")}}
+
 
+
{{domxref("Node.isSameNode()")}} {{obsolete_inline}}
+
 
+
{{domxref("Node.isSupported()")}} {{obsolete_inline}}
+
Returns a Boolean flag containing the result of a test whether the DOM implementation implements a specific feature and this feature is supported by the specific node.
+
{{domxref("Node.lookupPrefix()")}}
+
 
+
{{domxref("Node.lookupNamespaceURI()")}}
+
 
+
{{domxref("Node.normalize()")}}
+
Clean up all the text nodes under this element (merge adjacent, remove empty).
+
{{domxref("Node.removeChild()")}}
+
Removes a child node from the current element, which must be a child of the current node.
+
{{domxref("Node.replaceChild()")}}
+
Replaces one child {{domxref("Node")}} of the current one with the second one given in parameter.
+
{{domxref("Node.setUserData()")}} {{obsolete_inline}}
+
Allows a user to attach, or remove, {{domxref("DOMUserData")}} to the node.
+
 
+
+ +

Examples

+ +

Browse all child nodes

+ +

The following function recursively cycles all child nodes of a node and executes a callback function upon them (and upon the parent node itself).

+ +
function DOMComb (oParent, oCallback) {
+  if (oParent.hasChildNodes()) {
+    for (var oNode = oParent.firstChild; oNode; oNode = oNode.nextSibling) {
+      DOMComb(oNode, oCallback);
+    }
+  }
+  oCallback.call(oParent);
+}
+ +

Syntax

+ +
DOMComb(parentNode, callbackFunction);
+ +

Description

+ +

Recursively cycle all child nodes of parentNode and parentNode itself and execute the callbackFunction upon them as this objects.

+ +

Parameters

+ +
+
parentNode
+
The parent node (Node Object).
+
callbackFunction
+
The callback function (Function).
+
+ +

Sample usage

+ +

The following example send to the console.log the text content of the body:

+ +
function printContent () {
+  if (this.nodeValue) { console.log(this.nodeValue); }
+}
+
+onload = function () {
+  DOMComb(document.body, printContent);
+};
+ +

Remove all children nested within a node

+ +
Element.prototype.removeAll = function () {
+  while (this.firstChild) { this.removeChild(this.firstChild); }
+  return this;
+};
+ +

Sample usage

+ +
/* ... an alternative to document.body.innerHTML = "" ... */
+document.body.removeAll();
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#interface-node', 'Node')}}{{Spec2('DOM WHATWG')}}Removed the following properties: attributes, namespaceURI, prefix, and localName.
+ Removed the following methods: isSupported(), hasAttributes(), isSameNode(), getFeature(), setUserData(), and getUserData().
{{SpecName('DOM3 Core', 'core.html#ID-1950641247', 'Node')}}{{Spec2('DOM3 Core')}}The methods insertBefore(), replaceChild(), removeChild(), and appendChild() returns one more kind of error (NOT_SUPPORTED_ERR) if called on a {{domxref("Document")}}.
+ The normalize() method has been modified so that {{domxref("Text")}} node can also be normalized if the proper {{domxref("DOMConfiguration")}} flag is set.
+ Added the following methods: compareDocumentPosition(), isSameNode(), lookupPrefix(), isDefaultNamespace(), lookupNamespaceURI(), isEqualNode(), getFeature(), setUserData(), and getUserData().
+ Added the following properties: baseURI and textContent.
{{SpecName('DOM2 Core', 'core.html#ID-1950641247', 'Node')}}{{Spec2('DOM2 Core')}}The ownerDocument property was slightly modified so that {{domxref("DocumentFragment")}} also returns null.
+ Added the following properties: namespaceURI, prefix, and localName.
+ Added the following methods: normalize(), isSupported() and hasAttributes().
{{SpecName('DOM1', 'level-one-core.html#ID-1950641247', 'Node')}}{{Spec2('DOM1')}}Initial definition.
+ +

 

+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
getFeature(){{obsolete_inline}}{{CompatNo}}Supported from {{CompatGeckoDesktop("1.0")}} to {{CompatGeckoDesktop("6.0")}}.
+ Removed in {{CompatGeckoDesktop("7.0")}}
{{CompatUnknown}}{{CompatNo}}{{CompatNo}}
getUserData(), setUserData() and hasAttributes() {{deprecated_inline}}{{CompatNo}}Supported from {{CompatGeckoDesktop("1.0")}} to {{CompatGeckoDesktop("21.0")}}.
+ Removed in {{CompatGeckoDesktop("22.0")}}
{{CompatUnknown}}{{CompatNo}}{{CompatNo}}
isSameNode() {{obsolete_inline}}{{CompatNo}}Supported from {{CompatGeckoDesktop("1.0")}} to {{CompatGeckoDesktop("9.0")}}.
+ Removed in {{CompatGeckoDesktop("10.0")}}
{{CompatUnknown}}{{CompatNo}}{{CompatNo}}
isSupported() {{obsolete_inline}}{{CompatUnknown}}Supported from {{CompatGeckoDesktop("1.0")}} to {{CompatGeckoDesktop("21.0")}}.
+ Removed in {{CompatGeckoDesktop("22.0")}}
{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
attributes{{CompatNo}}Supported from {{CompatGeckoDesktop("1.0")}} to {{CompatGeckoDesktop("21.0")}}.
+ Moved to {{domxref("Element")}} in {{CompatGeckoDesktop("22.0")}}
{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
getFeature(){{obsolete_inline}}{{CompatNo}}Supported from {{CompatGeckoDesktop("1.0")}} to {{CompatGeckoDesktop("6.0")}}.
+ Removed in {{CompatGeckoDesktop("7.0")}}
{{CompatUnknown}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] Webkit and Blink incorrectly do not make Node inherit from {{domxref("EventTarget")}}.

diff --git a/files/es/web/api/node/insertarantes/index.html b/files/es/web/api/node/insertarantes/index.html new file mode 100644 index 0000000000..102d4dfbdd --- /dev/null +++ b/files/es/web/api/node/insertarantes/index.html @@ -0,0 +1,172 @@ +--- +title: Node.insertBefore() +slug: Web/API/Node/insertarAntes +tags: + - API + - DOM + - Nodo + - Referencia + - metodo +translation_of: Web/API/Node/insertBefore +--- +
{{APIRef("DOM")}}
+ +

El método Node.insertBefore() inserta un nodo antes del nodo de referencia como hijo de un nodo padre indicado. Si el nodo hijo es una referencia a un nodo ya existente en el documento, insertBefore() lo mueve de la posición actual a la nueva posición (no hay necesidad de eliminar el nodo de su nodo padre antes de agregarlo al algún nodo nuevo).

+ +

Esto significa que el nodo no puede estar en dos puntos del documento al simultáneamente. Por lo que si el nodo ya tiene un padre, primero se elimina el nodo, y luego se inserta en la nueva posición. {{domxref("Node.cloneNode()")}} puede utilizarse para hacer una copia de un nodo antes de insertarlo en un nuevo padre. Ten en cuenta que las copias hechas con cloneNode() no se mantendrán sincronizadas automáticamente.

+ +

Si el nodo de referencia es null, el nodo indicado se añadirá al final de la lista de hijos del nodo padre especificado.

+ +

Si el hijo proporcionado es un {{domxref("DocumentFragment")}}, el contenido completo del DocumentFragment se moverá a la lista de hijos del nodo padre indicado.

+ +

Sintaxis

+ +
var insertedNode = parentNode.insertBefore(newNode, referenceNode);
+
+ + + +

Si referenceNode es null, el newNode se insertará al final de la lista de nodos hijos.

+ +
+

referenceNode no es un parámetro opcional -- debes pasar explícitamente un Node o null. No proporcionándolo o pasando valores no válidos podría provocar un comportamiento distinto en diferentes versiones de navegadores.

+
+ +

Valor devuelto

+ +

El valor devuelto es el hijo añadido excepto cuando newNode es un {{domxref("DocumentFragment")}}, en cuyo caso se devuelve un {{domxref("DocumentFragment")}}.

+ +

Ejemplo

+ +

Ejemplo 1

+ +
<div id="parentElement">
+   <span id="childElement">foo bar</span>
+</div>
+
+<script>
+// Crear el nodo a insertar
+var newNode = document.createElement("span");
+
+// Obtener una referencia al nodo padre
+var parentDiv = document.getElementById("childElement").parentNode;
+
+// Comienzo del test [ 1 ] : Existe un childElement --> Todo funciona correctamente
+var sp2 = document.getElementById("childElement");
+parentDiv.insertBefore(newNode, sp2);
+// Fin del test [ 1 ]
+
+// Comienzo del test [ 2 ] : childElement no es del tipo undefined
+var sp2 = undefined; // No existe un nodo con id "childElement"
+parentDiv.insertBefore(newNode, sp2); // Implicit dynamic cast to type Node
+// Fin del test [ 2 ]
+
+// Comienzo del test [ 3 ] : childElement es de Tipo "undefined" ( string )
+var sp2 = "undefined"; // No existe un nodo con id "childElement"
+parentDiv.insertBefore(newNode, sp2); // Genera "Type Error: Invalid Argument"
+// Fin del test [ 3 ]
+</script>
+
+ +

Ejemplo 2

+ +
<div id="parentElement">
+  <span id="childElement">foo bar</span>
+</div>
+
+<script>
+// Crea un nuevo, elemento <span>
+var sp1 = document.createElement("span");
+
+// Obtener una referencia al elemento, antes de donde queremos insertar el elemento
+var sp2 = document.getElementById("childElement");
+// Obtener una referencia al nodo padre
+var parentDiv = sp2.parentNode;
+
+// Inserta un nuevo elemento en el DOM antes de sp2
+parentDiv.insertBefore(sp1, sp2);
+</script>
+
+ +

No existe el método insertAfter().  Puede ser emulado mediante la combinación del método con {{domxref("Node.nextSibling()")}}.

+ +

En el ejemplo anterior, sp1 podría insertarse después de sp2 usando:

+ +
parentDiv.insertBefore(sp1, sp2.nextSibling);
+ +

Si sp2 no tiene ningún hermano depués de él, entonces debe ser el último hijo — sp2.nextSibling devuelve null, y sp1 se inserta al final de la lista de nodos hijos (inmediatamente después de sp2).

+ +

Ejemplo 3

+ +

Inserta un elemento antes del primer elemento hijo, utilizando la propiedad firstChild.

+ +
// Obtener una referencia al elemento en el que se quiere insertar un nuevo nodo
+var parentElement = document.getElementById('parentElement');
+// Obtener una referencia al primer hijo
+var theFirstChild = parentElement.firstChild;
+
+// Crear un nuevo elemento
+var newElement = document.createElement("div");
+
+// Insertar el nuevo elemento antes que el primer hijo
+parentElement.insertBefore(newElement, theFirstChild);
+
+ +

Cuando el elemento no tiene ub primer hijo, entonces firstChild es null. Aun así, el elemento se añade al padre después del último hijo. Puesto que el elemento padre no tenía primer hijo, tampoco tiene último hijo. Por tanto, el nuevo elemento es el único elemento después de ser insertado.

+ +

Compatibilidad en navegadores

+ +

{{Compat("api.Node.insertBefore")}}

+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName('DOM WHATWG','#dom-node-insertbefore','Node.insertBefore')}}{{Spec2('DOM WHATWG')}}Corrige errores en el algoritmo de inserción
{{SpecName('DOM4','#dom-node-insertbefore','Node.insertBefore')}}{{Spec2('DOM4')}}Describe el algoritmo con mayor detalle
{{SpecName('DOM3 Core','core.html#ID-952280727','Node.insertBefore')}}{{Spec2('DOM3 Core')}}Sin cambios notables
{{SpecName('DOM2 Core','core.html#ID-952280727','Node.insertBefore')}}{{Spec2('DOM2 Core')}}Sin cambios notables
{{SpecName('DOM1','level-one-core.html#method-insertBefore','Node.insertBefore')}}{{Spec2('DOM1')}}Introducido
+ +

Ver también

+ + diff --git a/files/es/web/api/node/issamenode/index.html b/files/es/web/api/node/issamenode/index.html new file mode 100644 index 0000000000..205b6fd222 --- /dev/null +++ b/files/es/web/api/node/issamenode/index.html @@ -0,0 +1,110 @@ +--- +title: Node.isSameNode() +slug: Web/API/Node/isSameNode +translation_of: Web/API/Node/isSameNode +--- +
{{APIRef("DOM")}} {{Obsolete_header}}
+ +

Node.isSameNode() comprueba si dos nodos son iguales, es decir si hacen referencia al mismo objecto.

+ +
+

Warning: This method is no longer implemented in recent browsers.

+ +
// Instead of using
+node1.isSameNode(node2)
+
+// use
+node1 === node2 // or
+node1 == node2
+
+ +

Sintaxis

+ +
var isSameNode = node.isSameNode(other);
+
+ + + +

Especificaciones

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#interface-node', 'Node')}}{{Spec2('DOM WHATWG')}}Eliminado de la especificación.
{{SpecName('DOM3 Core', 'core.html#Node3-isSameNode', 'Node.isSameNode()')}}{{Spec2('DOM3 Core')}}Definición inicial
+ +

Compatibilidad entre navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatUnknown}}{{CompatGeckoDesktop("1.0")}}
+ {{CompatNo}} {{CompatGeckoDesktop("10.0")}}
{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatGeckoMobile("1.0")}}
+ {{CompatNo}} {{CompatGeckoMobile("10.0")}}
{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Ver además

+ + diff --git a/files/es/web/api/node/lastchild/index.html b/files/es/web/api/node/lastchild/index.html new file mode 100644 index 0000000000..0228c3264c --- /dev/null +++ b/files/es/web/api/node/lastchild/index.html @@ -0,0 +1,65 @@ +--- +title: Node.lastChild +slug: Web/API/Node/lastChild +tags: + - API + - DOM + - NecesitaCompatibilidadNavegador + - Propiedad + - Referencia +translation_of: Web/API/Node/lastChild +--- +
{{APIRef("DOM")}}
+ +

La propiedad de sólo lectura Node.lastChild devuelve el último hijo del nodo. Si su padre es un elemento, entonces el hijo es generalmente un nodo de element, nodo de texto o un nodo de comentario. Devuelve null si no hay elementos hijos.

+ +

Sintaxis

+ +
var nodoHijo= nodo.lastChild;
+
+ +

Ejemplo

+ +
var tr = document.getElementById("row1");
+var corner_td = tr.lastChild;
+
+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName('DOM WHATWG', '#dom-node-lastchild', 'Node.lastChild')}}{{Spec2('DOM WHATWG')}}Sin cambio
{{SpecName('DOM3 Core', 'core.html#ID-61AD09FB', 'Node.lastChild')}}{{Spec2('DOM3 Core')}}Sin cambio
{{SpecName('DOM2 Core', 'core.html#ID-61AD09FB', 'Node.lastChild')}}{{Spec2('DOM2 Core')}}Sin cambio
{{SpecName('DOM1', 'level-one-core.html#ID-61AD09FB', 'Node.lastChild')}}{{Spec2('DOM1')}}Definición inicial
+ +

Compatibilidad en navegador

+ + + +

{{Compat("api.Node.lastChild")}}

diff --git a/files/es/web/api/node/namespaceuri/index.html b/files/es/web/api/node/namespaceuri/index.html new file mode 100644 index 0000000000..f24b54d713 --- /dev/null +++ b/files/es/web/api/node/namespaceuri/index.html @@ -0,0 +1,145 @@ +--- +title: Node.namespaceURI +slug: Web/API/Node/namespaceURI +tags: + - API + - DOM + - NecesitaCompatilibidadNavegador + - Propiedad + - Referencia + - obsoleta +translation_of: Web/API/Node/namespaceURI +--- +
{{APIRef("DOM")}}{{obsolete_header}}
+ +

La propiedad de solo lectura Nodo.namespaceURI devuelve la URI del nodo, o null en caso de que el nodo no tenga espacio de nombres. Cuando el nodo es un documento, este devuelve el espacio de nombres del XML para el documento actual.

+ +
+

En DOM4 esta API fué movida desde Node a las interficies {{domxref("Element")}} y {{domxref("Attr")}}.

+
+ +

Sintaxis

+ +
namespace = node.namespaceURI
+ +

Ejemplo

+ +

En este fragmento, un nodo esá siendo examinado por su {{domxref("Node.localName")}} y namespaceURI. Si el namespaceURI devuelve el nombre de espaciosXUL y el localName devuelve "browser", entonces el nodo es entendido  a ser un XUL <browser/>.

+ +
if (node.localName == "browser" &&
+    node.namespaceURI == "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul") {
+  // Este es un navegador XUL
+}
+ +

Notas

+ +

Este no es un valor calculado que es el resultado de una búsqueda del espacio de nombres basada en la examinación de las declaraciones de un espacio de nombres en el ámbito. El espacio de nombres URI de un nodo es congelado ene l momento de su creación.

+ +

En Firefox 3.5 y anteriores, el espacio de nombres URI para los elementos HTML en los Documents HTML es null. En versiones psoteriores, en conformidad con HTML5, es https://www.w3.org/1999/xhtml como en XHTML. {{gecko_minversion_inline("1.9.2")}}

+ +

Para nodos de cualquier {{domxref("Node.nodeType")}} distintos de ELEMENT_NODE y ATTRIBUTE_NODE el valor de namespaceURI es siempre null.

+ +

Puedes crear un elemento con un namespaceURI concreto creando un método DOM de nivel 2 {{domxref("Document.createElementNS")}} y atributos con el método {{domxref("Element.setAttributeNS")}}.

+ +

Para la especificación Namespaces in XML, un atributo no hereda su espacio de nombres del elemento al que está sujeto. Si un atributo no es dado de manera explícita como espacio de nombres, entonces no los tiene.

+ +

El DOM no controla ni impone la validación del espacio de nombres. Depende de la aplicación DOM de hacer cualquier tipo de validación necesaria. Destacar también que el prefijo de espacio de nombre, una vez es asociado a un nodo enparticular, no puede ser modificado.

+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName("DOM3 Core", "core.html#ID-NodeNSname", "Node.namespaceURI")}}{{Spec2("DOM3 Core")}}Specifies the behavior when it's set to null.
{{SpecName("DOM2 Core", "core.html#Namespaces-Considerations", "DOM Level 2 Core: XML Namespaces")}}{{Spec2("DOM2 Core")}} 
{{SpecName("DOM2 Core", "core.html#ID-NodeNSname", "Node.namespaceURI")}}{{Spec2("DOM2 Core")}}Initial definition
+ +

Compatibilidad de navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Soporte básico{{CompatVersionUnknown}}
+ {{CompatNo}}46.0[1]
{{CompatVersionUnknown}}{{CompatVersionUnknown}}[2]
+ {{CompatNo}} {{CompatGeckoDesktop("48.0")}}[1]
{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Soporte básico{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}[2]
+ {{CompatNo}} {{CompatGeckoMobile("48.0")}}[1]
{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Esta API fue movida a las APIs {{domxref("Element")}} y {{domxref("Attr")}} de acuerdo con el standard de DOM4.

+ +

[2] Antes de Gecko 5.0 {{geckoRelease("5.0")}}, esta propiedad era de lectura-escritura; empezando con Gecko 5.0  es sólo lectura, siguiendo la especificación.

+ +

Ver también

+ + diff --git a/files/es/web/api/node/nextsibling/index.html b/files/es/web/api/node/nextsibling/index.html new file mode 100644 index 0000000000..188357f9c6 --- /dev/null +++ b/files/es/web/api/node/nextsibling/index.html @@ -0,0 +1,87 @@ +--- +title: Node.nextSibling +slug: Web/API/Node/nextSibling +tags: + - API + - DOM + - Gecko + - Nodo + - Propiedad +translation_of: Web/API/Node/nextSibling +--- +
{{APIRef("DOM")}}
+ +

La propiedad de sólo lectura Node.nextSibling devuelve el siguiente nodo con respecto al indicado en la lista de nodos ({{domxref("Node.childNodes","childNodes")}}) a la que este pertenece o null si el nodo especificado es el último en dicha lista.

+ +

Sintaxis

+ +
siguienteNodo = node.nextSibling
+
+ +

Notas

+ +
+ +

Gecko-based browsers insert text nodes into a document to represent whitespace in the source markup. + Therefore a node obtained, for example, using Node.firstChild or Node.previousSibling may refer to a + whitespace text node rather than the actual element the author intended to get.

+ +

See Whitespace in the DOM and + W3C DOM 3 FAQ: Why are some Text nodes empty? + for more information.

+ +

{{domxref("Element.nextElementSibling")}} debe ser utilizado para obtener el siguiente elemento ignorando cualquier nodo en blanco.

+
+ +

Ejemplo

+ +
<div id="div-01">Este es el div-01</div>
+<div id="div-02">Este es el div-02</div>
+
+<script type="text/javascript">
+var el = document.getElementById('div-01').nextSibling,
+    i = 1;
+
+console.log('Hermanos de div-01:');
+
+while (el) {
+  console.log(i + '. ' + el.nodeName);
+  el = el.nextSibling;
+  i++;
+}
+
+</script>
+
+/**************************************************
+  Lo siguiente se escribe en la consola cuando carga:
+
+      Nodos hermanos del div-01
+
+      1. #text
+      2. DIV
+      3. #text
+      4. SCRIPT
+
+**************************************************/
+
+ +

En el ejemplo anterior, se puede observar que los nodos #text se insertan en el DOM, donde se produce un espacio en blanco en el marcado entre las etiquetas (es decir, después de la etiqueta de cierre de un elemento y antes de la etiqueta de apertura del siguiente). No se crea ningún espacio en blanco entre los elementos insertados por la sentencia document.write.

+ +

La posible inclusión de los nodos de texto en el DOM se debe permitir cuando se atraviese el DOM utilizando nextSibling. Vea los recursos en la sección Notas.

+ +

Especificación

+ + + +

Compatibilidad en navegadores

+ +

{{Compat("api.Node.nextSibling")}}

+ +

Ver también

+ + diff --git a/files/es/web/api/node/nodename/index.html b/files/es/web/api/node/nodename/index.html new file mode 100644 index 0000000000..5865b21e21 --- /dev/null +++ b/files/es/web/api/node/nodename/index.html @@ -0,0 +1,107 @@ +--- +title: element.nodeName +slug: Web/API/Node/nodeName +tags: + - Referencia_DOM_de_Gecko +translation_of: Web/API/Node/nodeName +--- +
{{APIRef("DOM")}}
+ +

Resumen

+ +

Devuelve el nombre del nodo actual, en forma de cadena.

+ +

Sintaxis

+ +
varstr =node.nodeName;
+
+ +

str es una variable de cadena en la que se almacena el nombre del elemento actual.

+ +

nodeName es un atributo de solo-lectura.

+ +

Notas

+ +

Aquí tenemos el valor devuelto por varios tipos de nodo.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
InterfaznodeName
Attrigual que Attr.name
CDATASection"#cdata-section"
Comment"#comment"
Document"#document"
DocumentFragment"#document-fragment"
DocumentTypeigual que DocumentType.name
Elementigual que Element.tagName
Entitynombre de entity
EntityReferencenombre de la identidad de referencia
Notationnombre de la notación
ProcessingInstructionigual que ProcessingInstruction.target
Text"#text"
+ +

Ejemplo

+ +

Dado el siguiente código:

+ +
<div id="d1">hola mundo</div>
+<input type="text" id="t"/>
+
+ +

y el siguiente script:

+ +
var div1 = document.getElementById("d1");
+var text_field = document.getElementById("t");
+text_field.value = div1.nodeName;
+
+ +

En XHTML (o alguna otra forma de XML) el valor de text_field será "div". Sin embargo, en HTML, el valor de text_field sería "DIV".

+ +

Ten en cuenta que podríamos haber usado la propiedad tagName en su lugar, ya que nodeName tiene el mismo valor que tagName para un elemento. Presta atención, sin embargo, a que nodeName devolverá #text para los nodos de texto, mientras que tagName devolverá undefined.

+ +

Especificaciones

+ +

DOM Level 2 Core: Node.nodeName

+ +

DOM Level 3 Core: Node.nodeName

diff --git a/files/es/web/api/node/nodetype/index.html b/files/es/web/api/node/nodetype/index.html new file mode 100644 index 0000000000..1a1f28ac39 --- /dev/null +++ b/files/es/web/api/node/nodetype/index.html @@ -0,0 +1,95 @@ +--- +title: Node.nodeType +slug: Web/API/Node/nodeType +translation_of: Web/API/Node/nodeType +--- +
+
{{APIRef("DOM")}}
+ +
La propiedad de solo lectura Node.nodeType retornará un valor positivo entero representando el tipo de nodo.
+ +
 
+
+ +

Sintaxis

+ +
var type = node.nodeType;
+
+ +

la variable type será un entero positivo con alguno de los siguientes valores:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameValue
ELEMENT_NODE1
ATTRIBUTE_NODE {{deprecated_inline()}}2
TEXT_NODE3
CDATA_SECTION_NODE {{deprecated_inline()}}4
ENTITY_REFERENCE_NODE {{deprecated_inline()}}5
ENTITY_NODE {{deprecated_inline()}}6
PROCESSING_INSTRUCTION_NODE7
COMMENT_NODE8
DOCUMENT_NODE9
DOCUMENT_TYPE_NODE10
DOCUMENT_FRAGMENT_NODE11
NOTATION_NODE {{deprecated_inline()}}12
+ +

Ejemplo

+ +

Este es un ejemplo que verifica si el primer nodo dentro de un elemento tipo documento (document) es un comentario nodo, y si no lo es, muestra un mensaje.

+ +
var node = document.documentElement.firstChild;
+if (node.nodeType != Node.COMMENT_NODE)
+  console.log("You should comment your code well!");
+
+ +

Especificación

+ + diff --git a/files/es/web/api/node/nodevalue/index.html b/files/es/web/api/node/nodevalue/index.html new file mode 100644 index 0000000000..418cecdb77 --- /dev/null +++ b/files/es/web/api/node/nodevalue/index.html @@ -0,0 +1,86 @@ +--- +title: Node.nodeValue +slug: Web/API/Node/nodeValue +translation_of: Web/API/Node/nodeValue +--- +
+
{{APIRef("DOM")}}
+
+ +

La propiedad Nodo.nodeValue devuelve o actualiza el valor del nodo actual.

+ +

Sintaxis

+ +
valor= nodo.nodeValue;
+
+ +

valor es una cadena contenedora del valor del nodo actual, si es que tiene alguno.

+ +

Notas

+ +

Para el nodo en si, nodeValue devuelve null. Para texto, comentarios, y nodos CDATA, nodeValue devuelve el contenido de dicho nodo. Para nodos atributos, el valor del atributo es devuelto.

+ +

La siguiente table muestra los distintos valores retornados por los diferentes elementos.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Atributovalor del atributo
CDATASectioncontenido de la sección CDATA
CommentContenido del comentario
Documentnull
DocumentFragmentnull
DocumentTypenull
Elementnull
NamedNodeMapnull
EntityReferencenull
Notationnull
ProcessingInstructionTodo el contexto excluyendo el objetivo
TextContenido del nodo de texto
+ +

Cuando nodeValue es definido como null, actualizarlo no tiene efecto.

+ +

Especificación

+ + diff --git a/files/es/web/api/node/nodoprincipal/index.html b/files/es/web/api/node/nodoprincipal/index.html new file mode 100644 index 0000000000..55f02037bb --- /dev/null +++ b/files/es/web/api/node/nodoprincipal/index.html @@ -0,0 +1,33 @@ +--- +title: Nodo.nodoPrincipal +slug: Web/API/Node/nodoPrincipal +tags: + - API + - DOM + - Gecko + - Propiedad +translation_of: Web/API/Node +--- +
+
{{APIRef("DOM")}}
+{{Non-standard_header}} + +

La propiedad de solo loctura de Nodo.nodePrincipal devuelve el objeto {{Interface("nsIPrincipal")}} representando el contexto de seguridad del nodo actual.

+ +

{{Note("This property exists on all nodes (HTML, XUL, SVG, MathML, etc.), but only if the script trying to use it has chrome privileges.")}}

+ +

Sintaxis

+ +
principalObj = element.nodePrincipal
+
+ +

Notas

+ +

Esta propiedad es de solo lectura; Si intentamos editarla nos lanzará una excepción. Además, esta propiedad tan solo debería ser accesible desde código privilegiado

+ +

Especificación

+ +

No hay especificaciones.

+
+ +

 

diff --git a/files/es/web/api/node/ownerdocument/index.html b/files/es/web/api/node/ownerdocument/index.html new file mode 100644 index 0000000000..b1213ac818 --- /dev/null +++ b/files/es/web/api/node/ownerdocument/index.html @@ -0,0 +1,118 @@ +--- +title: Node.ownerDocument +slug: Web/API/Node/ownerDocument +tags: + - API + - DOM + - Nodo + - Propiedad + - Referencia +translation_of: Web/API/Node/ownerDocument +--- +
{{APIRef("DOM")}}
+ +

La propiedad de lectura ownerDocument de la interfaz {{domxref("Node")}} devuelve el objeto Document de más alto nivel/jerarquia para ese nodo.

+ +

Sintaxis

+ +
var document = element.ownerDocument;
+
+ +

Resultado

+ +

document es el objeto {{domxref("Document")}} de más alto nivel, con el que todos los nodos descendientes se crean. Si la propiedad se usa en un nodo que el mismo es un Document, el resultado es null.

+ +

Ejemplo

+ +
// dado un nodo "p",  coge el hijo que tenga la más alta jerarquia
+// del objeto Document
+
+var d = p.ownerDocument;
+var html = d.documentElement;
+
+
+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName("DOM4", "#dom-node-ownerdocument", "Node.ownerDocument")}}{{Spec2("DOM4")}}
{{SpecName("DOM3 Core", "core.html#node-ownerDoc", "Node.ownerDocument")}}{{Spec2("DOM3 Core")}}No change
{{SpecName("DOM2 Core", "core.html#node-ownerDoc", "Node.ownerDocument")}}{{Spec2("DOM2 Core")}}Initial definition
+ +

Compatibilidad de navegador

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Soporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}[1]6.0[2]{{CompatVersionUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Soporte básico{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Starting in Gecko 9.0 {{geckoRelease("9.0")}}, the ownerDocument of doctype nodes (that is, nodes for which {{domxref("Node.nodeType")}} is Node.DOCUMENT_TYPE_NODE or 10) is no longer null. Instead, the ownerDocument is the document on which document.implementation.createDocumentType() was called.

+ +

[2] http://msdn.microsoft.com/en-us/library/ie/ms534315(v=vs.85).aspx

diff --git a/files/es/web/api/node/parentnode/index.html b/files/es/web/api/node/parentnode/index.html new file mode 100644 index 0000000000..62bf77c4ff --- /dev/null +++ b/files/es/web/api/node/parentnode/index.html @@ -0,0 +1,105 @@ +--- +title: Node.parentNode +slug: Web/API/Node/parentNode +translation_of: Web/API/Node/parentNode +--- +
+
{{APIRef("DOM")}}
+ +
 
+
+ +

La propiedad de sólo lectura node.parentNode devuelve el padre del nodo especificado en el árbol.

+ +

Sintaxis

+ +
parentNode = node.parentNode
+ +

parentNode es el padre del nodo actual. El padre de un elemento es un nodo del tipo Element, un nodo Document, o un nodo DocumentFragment.

+ +

Ejemplo

+ +
if (node.parentNode) {
+  // Borra un nodo del árbol a no ser que
+  // esté ya en el árbol
+  node.parentNode.removeChild(node);
+}
+ +

Notas

+ +

Los nodos del tipo Document y DocumentFragment nunca van a tener un elemento padre, parentNode devolverá siempre null.

+ +

También devuelve null si el nodo acaba de ser creado y no está atado/incorporado al árbol.

+ +

Compatiblidad de navegador

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureEdgeFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Soporte básico{{CompatVersionUnknown}}{{CompatGeckoDesktop(1.0)}}0.2{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Soporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile(1)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Especificación

+ + + +

Ver también

+ + diff --git a/files/es/web/api/node/previoussibling/index.html b/files/es/web/api/node/previoussibling/index.html new file mode 100644 index 0000000000..e537d09a23 --- /dev/null +++ b/files/es/web/api/node/previoussibling/index.html @@ -0,0 +1,63 @@ +--- +title: Node.previousSibling +slug: Web/API/Node/previousSibling +tags: + - API + - DOM + - Gecko + - Propiedad +translation_of: Web/API/Node/previousSibling +--- +
+
{{APIRef("DOM")}}
+
+ +

La propiedad de sólo-lectura Node.previousSibling devuelve el nodo inmediatamente anterior al especificado en la lista de nodos {{domxref("Node.childNodes", "childNodes")}} de su padre, o null si el nodo especificado es el primero en dicha lista.

+ +

Sintaxis

+ +
nodoAnterior = nodo.previousSibling;
+
+ +

Ejemplo

+ +
<img id="b0">
+<img id="b1">
+<img id="b2">
+ +
console.log(document.getElementById("b1").previousSibling); // <img id="b0">
+console.log(document.getElementById("b2").previousSibling.id); // "b1"
+
+ +

Notas

+ + +

Gecko-based browsers insert text nodes into a document to represent whitespace in the source markup. + Therefore a node obtained, for example, using Node.firstChild or Node.previousSibling may refer to a + whitespace text node rather than the actual element the author intended to get.

+ +

See Whitespace in the DOM and + W3C DOM 3 FAQ: Why are some Text nodes empty? + for more information.

+ +

Para navegar en el sentido opuesto de la lista de nodos hijos se utiliza Node.nextSibling.

+ +

Especificación

+ + + +

Compatibilidad con navegadores

+ + + +

{{Compat("api.Node.previousSibling")}}

+ +

Ver también

+ + diff --git a/files/es/web/api/node/removechild/index.html b/files/es/web/api/node/removechild/index.html new file mode 100644 index 0000000000..423d482bb6 --- /dev/null +++ b/files/es/web/api/node/removechild/index.html @@ -0,0 +1,94 @@ +--- +title: Node.removeChild() +slug: Web/API/Node/removeChild +translation_of: Web/API/Node/removeChild +--- +
+
{{APIRef ( "DOM")}}
+ +

El método Node.removeChild() elimina un nodo hijo del DOM y puede devolver el nodo eliminado.

+ +

Sintaxis

+ +
+
var antiguoHijo = elemento.removeChild(child);
+O
+elemento.removeChild(child);
+
+
+ + + +

El hijo(child) eliminado aún existe en memoria pero ya no es parte del DOM. Con la primera forma de sintaxis mostrada, se puede reutilizar el nodo eliminado más tarde en el código, por medio de la referencia al objeto antiguoHijo. Sin embargo, en la segunda forma, la referencia a antiguoHijo se pierde, y suponiendo que el código no mantenga una referencia a ese objeto en alguna otra parte, inmediatamente será inutilizable e irrecuperable y será eliminada automáticamente de memoria después de poco tiempo.

+ +

Si hijo(child) no es en realidad hijo del nodo elemento, el método lanza una excepción. Esto también sucederá si child es en realidad hijo de elemento al momento de llamar al método, pero fue eliminado por un controlador(manejador) de eventos(event handler) invocado en el curso de tratar de eliminar el elemento. (e.g. blur).

+ +

Por lo tanto el método removeChild(child) lanza una excepción de 2 casos diferentes: 

+ +

1.      Si child es un hijo del elemento y por lo tanto existe en el DOM, pero se retiró el método lanza la siguiente excepción:

+ +

​​Uncaught NotFoundError: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.

+ +

2.      Si child no existe en el DOM de la página, el método emite la siguiente excepción:
+
+ Uncaught TypeError: Failed to execute 'removeChild' on 'Node': parameter 1 is not of type 'Node'.

+ +

Ejemplos

+ +
<!--Ejemplo 1 HTML-->
+<div id="top" align="center"> </div>
+ +
<!--Javascript-->
+// El método lanza la excepción correspondiente al (caso 2)
+var top = document.getElementById("top");
+var nested = document.getElementById("nested");
+var garbage = top.removeChild(nested);
+ +
<!--Ejemplo 2 HTML-->
+<div id="top">
+   <div id="anidados"></div> 
+</div>
+ +
<!--Javascript-->
+// Eliminando un elemento específico cuando se conoce su nodo padre
+var d = document.getElementById("top");
+var d_nested = document.getElementById("anidados");
+var throwawayNode = d.removeChild(d_nested);
+ +
<!--Javascript-->
+// Eliminando un elemento específico utilizando la propiedad parentNode, que siempre hace referencia al nodo padre de un nodo (nodoHijo.parentNode.).
+nodo var = document.getElementById("anidados");
+if (node.parentNode) {
+  node.parentNode.removeChild(nodo);
+}
+ +
<!--Javascript-->
+// Eliminando todos los hijos de un elemento
+elemento var = document.getElementById("top");
+while (element.firstChild) {
+  element.removeChild(element.firstChild);
+}
+ +

Notas:

+ +

removeChild() se debe invocar sobre el nodo padre del nodo que se va a eliminar.

+ +

Especificación

+ + + +

Vea también

+ + diff --git a/files/es/web/api/node/replacechild/index.html b/files/es/web/api/node/replacechild/index.html new file mode 100644 index 0000000000..e93f025bd9 --- /dev/null +++ b/files/es/web/api/node/replacechild/index.html @@ -0,0 +1,73 @@ +--- +title: Node.replaceChild() +slug: Web/API/Node/replaceChild +tags: + - API + - DOM + - Nodo + - Referencia + - metodo +translation_of: Web/API/Node/replaceChild +--- +
+
{{APIRef("DOM")}}
+
+ +

El método Node.replaceChild() reemplaza un nodo hijo del elemento especificado por otro.

+ +

Sintáxis

+ +
replacedNode = parentNode.replaceChild(newChild, oldChild);
+
+ + + +

Ejemplo

+ +
// <div>
+//  <span id="childSpan">foo bar</span>
+// </div>
+
+// crear un nodo con un elemento vacío
+// sin ID, atributos, ni contenido
+var sp1 = document.createElement("span");
+
+// darle un atributo id llamado 'newSpan'
+sp1.setAttribute("id", "newSpan");
+
+// crear algún contenido para el nuevo elemento
+var sp1_content = document.createTextNode("Nuevo elemento span para reemplazo.");
+
+// aplicar dicho contenido al nuevo elemento
+sp1.appendChild(sp1_content);
+
+// construir una referencia al nodo existente que va a ser reemplazado
+var sp2 = document.getElementById("childSpan");
+var parentDiv = sp2.parentNode;
+
+// reemplazar el nodo sp2 existente con el nuevo elemento span sp1
+parentDiv.replaceChild(sp1, sp2);
+
+// resultado:
+// <div>
+//   <span id="newSpan">Nuevo elemento span para reemplazo.</span>
+// </div>
+
+ +

Especificación

+ + + +

Ver también

+ + diff --git a/files/es/web/api/node/textcontent/index.html b/files/es/web/api/node/textcontent/index.html new file mode 100644 index 0000000000..46586e89d5 --- /dev/null +++ b/files/es/web/api/node/textcontent/index.html @@ -0,0 +1,98 @@ +--- +title: Node.textContent +slug: Web/API/Node/textContent +translation_of: Web/API/Node/textContent +--- +
{{APIRef("DOM")}}
+ +

La propiedad textContent de la interfaz {{domxref("Node")}} representa el contenido de texto de un nodo y sus dencendientes.

+ +
+

Nota: textContent y {{domxref("HTMLElement.innerText")}} son confundidos con facilidad, pero ambos son diferentes en varias formas importantes.

+
+ +

Sintaxis

+ +
var text = Node.textContent;
+Node.textContent = string;
+
+ +

Valor devuelto

+ +

Una cadena de texto o null

+ +

Descripción

+ +

Al obtener esta propiedad:

+ + + +

Estableciendo textContent en un nodo elimina todos sus hijos y los reemplaza con un solo nodo de texto con el valor dado.

+ +

Diferencias con innerText

+ +

Internet Explorer introdujo elemento.innerText. La intención es muy parecida, con un par de diferencias:

+ + + +

Diferencias con innerHTML

+ +

innerHTML retorna el HTML como su nombre indica. Con bastante frecuencia, para leer o escribir texto en un elemento, la gente usa innerHTML. textContent debería usarse en su lugar. Ya que el texto no es procesado es más probable que tenga mejor rendimiento. Además, esto evita un vector de ataques XSS.

+ +

Ejemplo

+ +
// Dado el siguiente fragmento HTML:
+//   <div id="divA">Esto <span>es</span>un texto</div>
+
+// Lee el contenido textual:
+var text = document.getElementById("divA").textContent;
+// |text| contiene la cadena "Esto es un texto".
+
+// Escribe el contenido textual:
+document.getElementById("divA").textContent = "Esto es un nuevo texto";
+// El HTML "divA" ahora contiene una nueva cadena:
+//   <div id="divA">Esto es un nuevo texto</div>
+
+ +

Compatibilidad con navegadores

+ + + +

{{Compat("api.Node.textContent")}}

+ +

Especificación

+ + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName('DOM WHATWG','#dom-node-textcontent','Node.textContent')}}{{Spec2('DOM WHATWG')}}Sin cambios desde DOM 4
{{SpecName('DOM4','#dom-node-textcontent','Node.textContent')}}{{Spec2('DOM4')}} 
{{SpecName('DOM3 Core','core.html#Node3-textContent','Node.textContent')}}{{Spec2('DOM3 Core')}}Introducido
+ +

 

-- cgit v1.2.3-54-g00ecf