What is the error in counting the A tags?

0

var totales = 0;
function buscarLinks(){
var links = document.getElementsByTagName("A");
var i=0,
    linkse=links.length;
for(;i<linkse;i++){
  if(links[i].href == 'prueba') totales++;
  
}
}
console.log(totales);
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body onload="buscarLinks();">
  
  <a href="prueba">prueba real 1</a>
  <hr>
  <a href="http://gg">prueba FALSA</a>
  <hr>
  <a href="prueba">prueba real 2</a>
  
</body>
</html>

I try to count the A tags but I always get 0, why?

    
asked by Eduardo Sebastian 10.08.2017 в 19:36
source

2 answers

1

The error is where you make the comparison:

if(links[i].href == 'prueba') When printing href within for

for(;i<linkse;i++){
  console.log(links[i].href)
}
/* imprime:
https://stacksnippets.net/prueba
http://gg/
https://stacksnippets.net/prueba
*/

therefore the comparison if(links[i].href == 'prueba')

will always be false     
answered by 10.08.2017 / 20:08
source
0

Try this:

var totales = 0;
function buscarLinks(){
    var links = document.getElementsByTagName("A");
    for(var i=0; i<links.length; i++){
      if(links[i].getAttribute('href') == 'prueba') {
          totales++;
      }
      console.log(totales);
    }
}

What was happening to you was that apart from that the comparison was always going to be incorrect since .href is returning the URL entera , but if you only collect the attribute href will return only prueba , and on the other hand you make the console.log at the time when the Script is loaded , but it turns out that the buscarLinks() function is called once the page is loaded, so you always resultaba 0 since the function buscarLinks() had not yet been executed.

I hope it helps.

    
answered by 10.08.2017 в 20:24