indexof is not recognized inside the for

Asked

Viewed 84 times

0

Hello I am trying to run this code so that it captures all the links of a page, it works all ok, the problem is that I want to find links that contain a certain word using index but is giving the following error in the log..

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

Some way to resolve this so that you only find the links indicated by index ?

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');
} 

2 answers

2

You have 2 problems:

You are taking 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 index 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' );
} 

0

You’re trying to use indexOf in objects collected in getElementsByTagName.

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

Appendage 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');
} 

Browser other questions tagged

You are not signed in. Login or sign up in order to post.