Tema: pinche for
Ver Mensaje Individual
  #10 (permalink)  
Antiguo 08/11/2011, 01:02
JaiMe_
 
Fecha de Ingreso: junio-2011
Ubicación: New York City
Mensajes: 13
Antigüedad: 12 años, 10 meses
Puntos: 3
Respuesta: pinche for

Lo primero:

* Antes de operar con el DOM, debes estar seguro que ha sido cargado y esta listo. Para esto puedes agregar un event handler usando window.onload (alternativamente, lo mejor seria usar el metodo addEventListener de la especificación del DOM Level 2)

* para obtener el attributo de un nodo de DOM debes usar el metodo getAttribute(<attributo>)

* El for loop se ejecuta mas veces del numero necesario, lo cual provoca un error.

Este código funciona:

Código Javascript:
Ver original
  1. window.onload = function(){
  2.     var enlaces = document.getElementsByTagName("a");
  3.     var dir = "http://www.prueba";
  4.     var numero = 0;
  5.     var b, c;
  6.  
  7.     for (var i = 0, l = enlaces.length; i < l ;i++){  
  8.         b = enlaces[i].getAttribute('href');
  9.         c = b.slice(0,17);
  10.         if (c === dir) { numero++; }
  11.     }
  12.     alert(numero + " veces fueron iguales");
  13. };


Código HTML:
Ver original
  1. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="es">
  2.   <head>
  3.     <title>prueba</title>
  4.     <script type="text/javascript">
  5.       // codigo aca
  6.     </script>
  7. </head>
  8.  
  9.  
  10.   <a href="http://www.prueba1.com">1 aa</a>
  11.   <a href="http://www.prueba2.com">2 t</a>
  12.   <a href="http://www.prueba3.com">3</a>
  13.   <a href="http://www.prueba4.com">4</a>
  14.   <a href="http://www.prueba5.com">5</a>
  15.  
  16.  
  17. </body>
  18. </html>