0

Could anyone offer an elegant snippet of Javascript that will change URLs like these

<a href="joebiden" title="Twitter" aria-label="Twitter">Joe</a>
<a href="berniesanders" title="Twitter" aria-label="Twitter">Bernie</a>

To URLs like these:

<a href="https://twitter.com/joebiden" title="Twitter" aria-label="Twitter">Joe</a>
<a href="https://twitter.com/berniesanders" title="Twitter" aria-label="Twitter">Bernie</a>

So that the twitter URL is prepended?

  • Does this answer your question? [How to prepend url with http:// using stringWithFormat in Swift](https://stackoverflow.com/questions/24247263/how-to-prepend-url-with-http-using-stringwithformat-in-swift) – chandu komati Mar 18 '20 at 03:14

1 Answers1

1

This snippet looks for <a> elements with an aria-label value of "Twitter", and prepends "https://twitter.com/" to the existing href value.

for (let a of Object.values(document.getElementsByTagName('a'))) {
  if (a.getAttribute('aria-label') === 'Twitter') {
    a.setAttribute('href', 'https://twitter.com/' + a.getAttribute('href'))
  }
}

// Show results
for (let a of Object.values(document.getElementsByTagName('a'))) {
    console.log(a.getAttribute('href'));
}
<a href="joebiden" title="Twitter" aria-label="Twitter">Joe</a>
<a href="berniesanders" title="Twitter" aria-label="Twitter">Bernie</a>
cybersam
  • 63,203
  • 6
  • 53
  • 76
  • You are quite the bomb. Thank you. :) – Asher Black Mar 18 '20 at 03:53
  • I did this to make it conditional on the link even being populated: `code` for (let a of Object.values(document.getElementsByTagName('a'))) { if (a.getAttribute('aria-label') === 'Twitter') { if (a.getAttribute("href") !== "") { a.setAttribute('href', 'https://twitter.com/' + a.getAttribute('href')) // Show results for (let a of Object.values(document.getElementsByTagName('a'))) { console.log(a.getAttribute('href')); } } } } `code` – Asher Black Mar 18 '20 at 05:13