diff options
| author | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:41:45 -0500 |
|---|---|---|
| committer | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:41:45 -0500 |
| commit | 1109132f09d75da9a28b649c7677bb6ce07c40c0 (patch) | |
| tree | 0dd8b084480983cf9f9680e8aedb92782a921b13 /files/es/web/api/nodelist | |
| parent | 4b1a9203c547c019fc5398082ae19a3f3d4c3efe (diff) | |
| download | translated-content-1109132f09d75da9a28b649c7677bb6ce07c40c0.tar.gz translated-content-1109132f09d75da9a28b649c7677bb6ce07c40c0.tar.bz2 translated-content-1109132f09d75da9a28b649c7677bb6ce07c40c0.zip | |
initial commit
Diffstat (limited to 'files/es/web/api/nodelist')
| -rw-r--r-- | files/es/web/api/nodelist/foreach/index.html | 132 | ||||
| -rw-r--r-- | files/es/web/api/nodelist/index.html | 123 |
2 files changed, 255 insertions, 0 deletions
diff --git a/files/es/web/api/nodelist/foreach/index.html b/files/es/web/api/nodelist/foreach/index.html new file mode 100644 index 0000000000..4cb55533e1 --- /dev/null +++ b/files/es/web/api/nodelist/foreach/index.html @@ -0,0 +1,132 @@ +--- +title: NodeList.prototype.forEach() +slug: Web/API/NodeList/forEach +tags: + - DOM + - Iterable + - Métodos + - NodeList + - Referencia + - Web +translation_of: Web/API/NodeList/forEach +--- +<p>{{APIRef("DOM")}}</p> + +<p>El método<strong><code>forEach()</code></strong> de la interfase{{domxref("NodeList")}} llama a la función callback proporcionada como parámetro una vez para cadapar de valores en la lista, en el orden en que se insertaron.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><em>nodeList.</em>forEach<em>(callback[, thisArg]);</em> +</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><code>callback</code></dt> + <dd>Función a ser ejecutada paracada elemento, tomando eventualmente 3 argumentos: + <dl> + <dt><em><code>currentValue</code></em></dt> + <dd>El valor que esta siendo procesado en la lista de nodos.</dd> + <dt><code><em>currentIndex</em></code></dt> + <dd>El índice del elemento que esta siendo procesado en la lista de nodos.</dd> + <dt><em><code>listObj</code></em></dt> + <dd>El objeto NodeList al que se está aplicando el método<code>forEach()</code>.</dd> + </dl> + </dd> + <dt><code>thisArg</code><code> {{Optional_inline}}</code></dt> + <dd>Valor a ser usado como {{jsxref("this")}} al ejecutar<code>callback</code>.</dd> +</dl> + +<h3 id="Valor_Retornado">Valor Retornado</h3> + +<p>{{jsxref('undefined')}}.</p> + +<h2 id="Excepciones">Excepciones</h2> + +<p><em>Ninguna</em>.</p> + +<h2 id="Ejemplo">Ejemplo</h2> + +<pre class="brush: js;highlight:[6]">var nodo = document.createElement("div"); +var infante1 = document.createElement("p"); +var infante2 = document.createTextNode("hey"); +var infante3 = document.createElement("span"); + +nodo.appendChild(infante1); +nodo.appendChild(infante2); +nodo.appendChild(infante3); + +var list = nodo.childNodes; + +list.forEach( + function(currentValue, currentIndex, listObj) { + console.log(currentValue + ', ' + currentIndex + ', ' + this); + }, + 'miEsteArg' +);</pre> + +<p>resulta en:</p> + +<pre>[object HTMLParagraphElement], 0, miEsteArg +[object Text], 1, miEsteArg +[object HTMLSpanElement], 2, miEsteArg</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p>Este {{Glossary("Polyfill","polyfill")}} le da compatibilidad a todos los navegadores que soportan <a href="https://caniuse.com/#search=es5">ES5</a>:</p> + +<pre class="brush: js">if (window.NodeList && !NodeList.prototype.forEach) { + NodeList.prototype.forEach = function (callback, thisArg) { + thisArg = thisArg || window; + for (var i = 0; i < this.length; i++) { + callback.call(thisArg, this[i], i, this); + } + }; +}</pre> + +<p>ó</p> + +<pre class="brush: js">if (window.NodeList && !NodeList.prototype.forEach) { + NodeList.prototype.forEach = Array.prototype.forEach; +}</pre> + +<p>El comportamiento ateriror esta implementado en muchos navegadores. NodeList.prototype.forEach (Chrome, Firefox for example).</p> + +<h2 id="Especificaciones">Especificaciones</h2> + +<p>Especificación</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col"></th> + <th scope="col">Status</th> + <th scope="col">Comentarios</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('DOM WHATWG', '#interface-nodelist', 'NodeList')}}</td> + <td>{{ Spec2('DOM WHATWG') }}</td> + <td>Define<code>NodeList</code> como<code><Nodo>iterable</code></td> + </tr> + <tr> + <td>{{SpecName("WebIDL", "#es-forEach", "forEach")}}</td> + <td>{{Spec2("WebIDL")}}</td> + <td>Define<code>forEach</code>en declaraciones<code>iterables</code></td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_en_Navegadores">Compatibilidad en Navegadores</h2> + +<div class="hidden">La tabla de compatibilidades en esta página es generada con datos estructurados. Si quisieras contribuir a los datos, revisa<a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a>y envíanos una solicitud de pull.</div> + +<p>{{Compat("api.NodeList.forEach")}}</p> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{domxref("Node")}}</li> + <li>{{domxref("NodeList")}}</li> +</ul> diff --git a/files/es/web/api/nodelist/index.html b/files/es/web/api/nodelist/index.html new file mode 100644 index 0000000000..444a6cbb07 --- /dev/null +++ b/files/es/web/api/nodelist/index.html @@ -0,0 +1,123 @@ +--- +title: NodeList +slug: Web/API/NodeList +tags: + - API + - DOM + - Interfaz + - NodeList +translation_of: Web/API/NodeList +--- +<div>{{APIRef("DOM")}}</div> + +<p>Los objetos <strong><code>NodeList</code></strong> son colecciones de nodos como los devueltos por propiedades como {{domxref ("Node.childNodes")}} y el método {{domxref ("document.querySelectorAll ()")}}..</p> + +<div class="note"> +<p>Aunque <code>NodeList</code> no es un <code>Array</code>, es posible iterar sobre él utilizando <code>forEach()</code>. También puede convertirse a un <code>Array</code> usando <code>Array.from</code>.</p> + +<p>Sin embargo, algunos navegadores antiguos no han implementado <code>NodeList.forEach()</code> ni <code>Array.from()</code>. Pero esas limitaciones pueden eludirse utilizando {{jsxref("Array.forEach()", "Array.prototype.forEach()")}} (más en este documento).</p> +</div> + +<p>En algunos casos, <code>NodeList</code> es una colección <em>en vivo</em>, lo que significa que los cambios en el DOM se reflejan en la colección. Por ejemplo, {{domxref ("Node.childNodes")}} está en vivo:</p> + +<pre class="brush: js">var parent = document.getElementById('parent'); +var child_nodes = parent.childNodes; +console.log(child_nodes.length); // asumamos "2" +parent.appendChild(document.createElement('div')); +console.log(child_nodes.length); // debería imprimir "3" +</pre> + +<p>En otros casos, <code>NodeList</code> es una colección estática, lo que significa que cualquier cambio posterior en el DOM no afecta el contenido de la colección. {{domxref ("document.querySelectorAll ()")}} devuelve un <code>NodeList</code> estático.</p> + +<p>Es bueno tener en cuenta esta distinción cuando elige cómo iterar sobre los elementos en <code>NodeList</code>, y cómo guarda en caché la longitud de la lista en particular.</p> + +<h2 id="Propiedades">Propiedades</h2> + +<dl> + <dt>{{domxref("NodeList.length")}}</dt> + <dd>El número de nodos en la <code>NodeList</code>.</dd> +</dl> + +<h2 id="Métodos">Métodos</h2> + +<dl> + <dt>{{domxref("NodeList.item()")}}</dt> +</dl> + +<dl> + <dd>Devuelve un elemento en la lista por su índice, o <code>null</code> si el índice está fuera de límites; se puede utilizar como una alternativa para acceder simplemente a <code>nodeList[idx]</code> (que en cambio devuelve indefinido cuando idx está fuera de límites).</dd> + <dt>{{domxref("NodeList.entries()")}}</dt> + <dd>Devuelve un {{jsxref ("Iteration_protocols", "iterator")}} que permite pasar por todos los pares clave / valor contenidos en este objeto.</dd> + <dt>{{domxref("NodeList.forEach()")}}</dt> + <dd>Ejecuta una función proporcionada una vez por elemento <code>NodeList</code>.</dd> + <dt>{{domxref("NodeList.keys()")}}</dt> + <dd>Devuelve un {{jsxref ("Iteration_protocols", "iterator")}} que permite pasar por todas las claves de los pares clave / valor contenidos en este objeto.</dd> + <dt>{{domxref("NodeList.values()")}}</dt> + <dd>Devuelve un {{jsxref ("Iteration_protocols", "iterator")}} que permite recorrer todos los valores de los pares clave / valor contenidos en este objeto.</dd> +</dl> + +<h2 id="Ejemplo">Ejemplo</h2> + +<p>Es posible iterar sobre los items en un <code>NodeList</code> usando:</p> + +<pre class="brush: js">for (var i = 0; i < myNodeList.length; i++) { + var item = myNodeList[i]; // No es necesario llamar a myNodeList.item(i) en JavaScript +} +</pre> + +<p>No se sienta tentado a <code><a href="/en-US/docs/JavaScript/Reference/Statements/for...in" title="JavaScript/ Reference/Statements/for...in">for...in</a></code> or <code><a href="/en-US/docs/JavaScript/Reference/Statements/for_each...in" title="JavaScript/ Reference/Statements/for each...in">for each...in</a></code> para enumerar los elementos en la lista, ya que eso también enumerará la longitud y las propiedades del elemento de <code>NodeList</code> y causará errores si su secuencia de comandos asume que solo tiene que tratar con objetos {{domxref ("element")}}. Además, <code>for..in</code> no garantiza visitar las propiedades en ningún orden en particular.</p> + +<p>Los bucles <code><a href="/en-US/docs/JavaScript/Reference/Statements/for...of" title="/en-US/docs/JavaScript/Reference/Statements/for...of">for...of</a></code> harán un bucle sobre los objetos <code>NodeList</code> correctamente:</p> + +<pre class="brush: js">var list = document.querySelectorAll( 'input[type=checkbox]' ); +for (var item of list) { + item.checked = true; +} +</pre> + +<p>Los navegadores recientes también son compatibles con los métodos de iteración, {{domxref("NodeList.forEach()", "forEach()")}}, así como {{domxref("NodeList.entries()", "entries()")}}, {{domxref("NodeList.values()", "values()")}}, y {{domxref("NodeList.keys()", "keys()")}}</p> + +<p>También hay una forma compatible con Internet Explorer de usar {{jsxref ("Array.forEach ()", "Array.prototype.forEach")}} para la iteración.</p> + +<pre class="brush: js">var list = document.querySelectorAll( 'input[type=checkbox]' ); +Array.prototype.forEach.call(list, function (item) { + item.checked = true; +});</pre> + +<h2 id="Especificaciones" name="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('DOM WHATWG', '#interface-nodelist', 'NodeList')}}</td> + <td>{{ Spec2('DOM WHATWG') }}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('DOM3 Core', 'core.html#ID-536297177', 'NodeList')}}</td> + <td>{{ Spec2('DOM3 Core') }}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('DOM2 Core', 'core.html#ID-536297177', 'NodeList')}}</td> + <td>{{ Spec2('DOM2 Core') }}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('DOM1', 'level-one-core.html#ID-536297177', 'NodeList')}}</td> + <td>{{ Spec2('DOM1') }}</td> + <td>Definición inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_en_navegadores">Compatibilidad en navegadores</h2> + +<p>{{Compat("api.NodeList")}}</p> |
