List links on a page

0

Good morning! I have this script that lists all the links of a page, but does not bring the name of the link but only the address, can you name the link instead of the address?

javascript: var a = document.getElementsByTagName('a');var b = a.length; if(b != 0){ document.write('<h1> Lista de Links </h1> '); for (i = 0; i < b; i++){ document.write('<pre><a href=\'' + a[i] + '\'>' + a[i] + '</a>' + '</pre> ');}} else{ document.write('Nenhum link encontrado');}
    
asked by anonymous 06.02.2018 / 16:26

3 answers

2

It's what you're specifying in the code to bring the URL as the name of the link. To get the URL of the item listed:

a[i].href

To get the name of the link:

a[i].innerHTML

Then following your code will look like this:

javascript: var a = document.getElementsByTagName('a');var b = a.length; if(b != 0){ document.write('<h1> Lista de Links </h1> '); for (i = 0; i < b; i++){ document.write('<pre><a href=\'' + a[i].href + '\'>' + a[i].innerHTML + '</a>' + '</pre> ');}} else{ document.write('Nenhum link encontrado');}

Remember that the JAVASCRIPT: protocol is no longer used by default, now if you are wanting to use as a link is partially correct.

If you are going to create a browser utility I recommend creating browser, Chrome, Opera and Firefox applications. I have not used Edge yet to know if they have it.

    
06.02.2018 / 16:46
1

In fact, it brings all the elements together. Only you are printing the a element within the attribute of another a element.

Do this:

const a = document.getElementsByTagName('a');

for (let b of a) {
    document.write('<pre><a href=\'' + b.getAttribute("href") + '\'>' + b.innerText + '</a>' + '</pre> ');
}
    
06.02.2018 / 16:35
0

You can trade for this:

// Capturamos todos os links:
const links = document.getElementsByTagName('a');

// Criamos a div que irá conter todos os links.
const div = document.createElement('div');
div.innerHTML = '<h1>Lista de Links</h1><br><br><br>';
div.style.padding = '20px';

// Iteramos sobre todos os links.
for (let i = 0; i < links.length; i++) {
  const self = links[i];

  // Caso não haja texto:
  if (self.innerText === '') continue;

  // Criar o elemento da iteração atual
  // e incluí-lo na div que criamos acima.
  const code = document.createElement('code');
  code.innerHTML = '<a href="${self.href}">${self.innerText}</a><br><br>';

  div.appendChild(code);
}

// Substituir todo o conteúdo do body
// pela lista de links.
document.body.innerHTML = div.outerHTML;

I tried to explain with comments through the code.

Good afternoon!

    
06.02.2018 / 16:38