Change href of multiple labels to with document.getElementsByClassName

3

I need to change the href with JavaScript (without Jquery) in the following code:

<div class="set">
    <a href="https://snapwidget.com/embed/4972t07">link a</a>
</div>
<div class="set">
    <a href="https://snapwidget.com/embed/4s972t07">link b</a>
</div>
<div class="set">
    <a href="https://snapwidget.com/embed/4s9720t7d">link c</a>
</div>

I need to change it by the following URL: https://www.instagram.com/leonard_avi/ , when you load the entire document (automatically without clicking)

    
asked by Leonard J. Ávila S. 20.01.2018 в 02:01
source

1 answer

1

You can do it with querySelectorAll .

General Replacement

Here: document.querySelectorAll('div.set > a') the widths of the div whose class is called set are selected.

Then you go through them in a loop and make the change.

function cambiarLinks() {
  var nuevoLink = 'https://www.instagram.com/leonard_avi/';
  var eSet = document.querySelectorAll('div.set > a');
  var i = eSet.length;

  while (i--) {
    eSet[i].href = nuevoLink;
    console.log('Cambiado a : '+nuevoLink);
  }
}
window.onload = cambiarLinks;
<div class="set">
  <a href="https://snapwidget.com/embed/4972t07">link a</a>
</div>
<div class="set">
  <a href="https://snapwidget.com/embed/4s972t07">link b</a>
</div>
<div class="set">
  <a href="https://snapwidget.com/embed/4s9720t7d">link c</a>
</div>

Partial replacement

In this example, the last link element is retained. It would be useful in cases where you want to change everything, saving what makes the difference at the end of the link.

function cambiarLinks() {
  var nuevoLink = 'https://www.instagram.com/leonard_avi/';
  var eSet = document.querySelectorAll('div.set > a');
  var i = eSet.length;

  while (i--) {
    var viejoLink=eSet[i].href;
    var viejoUltimo=viejoLink.substr(viejoLink.lastIndexOf('/') + 1);
    var nuevoFinal=nuevoLink+viejoUltimo;
    eSet[i].href = nuevoFinal;
    console.log('Cambiado a : '+nuevoFinal);
  }
}
window.onload = cambiarLinks;
<div class="set">
  <a href="https://snapwidget.com/embed/4972t07">link a</a>
</div>
<div class="set">
  <a href="https://snapwidget.com/embed/4s972t07">link b</a>
</div>
<div class="set">
  <a href="https://snapwidget.com/embed/4s9720t7d">link c</a>
</div>
    
answered by 20.01.2018 / 02:29
source