indexOf is not recognized within the for

0

Hello, I am trying to execute this code so that it captures all the links on a page, everything works ok, the problem is that I want to find links that contain a certain word using indexOf error in log ..

Uncaught TypeError: str.IndexOf is not a function
at pesq (<anonymous>:22:14)
at <anonymous>:8:1

Any way to resolve this so that it only finds the particular links indicated by indexOf ?

javascript: var w = window.open('', '', 'height=300, width=300');
var a = document.getElementsByTagName('a');
var b = a.length;

if(b != 0){ 
   w.document.write('<h1>Lista de Links </h1>'); 

for (i = 0; i < b; i++){ 

var str = a[i];

 if(str.indexOf('palavra')){
 w.document.write('<pre><a href=\'' + a[i] + '\'>' + a[i] + '</a>' + '</pre>');
}


}
}else{ 
    w.document.write('Nenhum link encontrado');
} 
    
asked by anonymous 13.04.2018 / 19:53

2 answers

2

You have 2 problems:

You are catching the element instead of the href attribute.

// Nesse caso, a[i] é um elemento do DOM
// var str = a[i];

// O correto seria:
var str = a[i].href

The indexOf method returns -1 when it does not find the character, so all links not started with 'word' would be displayed

// Alternativa 1
if ( ~str.indexOf('palavra') ) 

// Alternativa 2
if ( str.indexOf('palavra') > -1 ) 

See your code working:

var janela = window.open( '', '', 'height=300, width=300' );
var elementos = document.getElementsByTagName( 'a' );
var size = elementos.length;

if ( size ) {
  janela.document.write( '<h1>Lista de Links </h1>' );

  for ( i = 0; i < size; i++ ) {
    var linkDoElemento = elementos[ i ].href;
    var textoDoElemento = elementos[ i ].textContent;
    if ( ~linkDoElemento.indexOf( 'stack' ) ) {
        janela.document.write( '<pre><a href=\'' + linkDoElemento + '\'>' + textoDoElemento.trim() + '</a>' + '</pre>' );
    }
  }
} else {
  janela.document.write( 'Nenhum link encontrado' );
} 
    
13.04.2018 / 20:44
0

You are trying to use indexOf on objects collected in getElementsByTagName .

If you want to check the text on each object, you can use innerHTML (it will even check tags) or textContent (text only).

Add textContent (or innerHTML as appropriate) to a[i] :

javascript: var w = window.open('', '', 'height=300, width=300');
var a = document.getElementsByTagName('a');
var b = a.length;

if(b != 0){ 
   w.document.write('<h1>Lista de Links </h1>'); 
for (i = 0; i < b; i++){ 

var str = a[i].textContent;

 if(str.indexOf('palavra')){
 w.document.write('<pre><a href=\'' + a[i].textContent + '\'>' + a[i].textContent + '</a>' + '</pre>');
}


}
}else{ 
    w.document.write('Nenhum link encontrado');
} 
    
13.04.2018 / 20:04