Listing links from a page

Asked

Viewed 187 times

0

Good morning! I have this script that lists all the links of a page, but it does not bring the name of the link but only the address, it has to bring the name of 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');}

3 answers

2


It is that you yourself are specifying in the code to bring the URL as the link name. To get the URL of the listed item:

a[i].href

To get the link name:

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 want to use as a link is partially correct.

If it is to create a utility for browsers I advise creating browser applications, Chrome, Opera and Firefox. I haven’t used the edge yet.

  • worked perfectly, thank you

1

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

Do it that way:

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

for (let b of a) {
    document.write('<pre><a href=\'' + b.getAttribute("href") + '\'>' + b.innerText + '</a>' + '</pre> ');
}
  • This stopped the navigator, but thank you

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!

  • This stopped the navigator, but thank you

  • Did you put it on the console or URL? In this script, you should put it on the console. To do this, press F12 and then go to the console tab. Paste the code there and enter.

  • Ah yes now I understand, thank you

Browser other questions tagged

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