Search code examples
jqueryreplacehyperlink

Replace multiple link with button


I have a code that works to replace the url of a link with a given id

I want this code to work for multiple links and player with the same specified id or class

I have one button that should change all together

Can you guide me or help me?

$(document).ready(function(){
$('#change').on('click', function(e) {
 var purl = $("#urlchange").attr("href");
purl = purl .replace("dl.faz2music.ir", "up.faz2music.ir");
 $("#urlchange").attr("href",purl);
notice.showToast({text: 'Links converted',type: 'success',showClose: true});
});
});
<button id="change" class="ltr">change link's</button>

<a href="https://dl.faz2music.ir/download/3712434/Ahmad Solo - Shazdeh Pesar [320].mp3"  id="urlchange">Download</a>
<a href="https://dl.faz2music.ir/download/3712434/Ahmad Solo - Shazdeh Pesar [128].mp3"  id="urlchange">Download</a>

<audio><source type="audio/mp3" src="https://dl.faz2music.ir/download/3712434/Ahmad Solo - Shazdeh Pesar [320].mp3" id="urlchange"></audio>
<audio><source type="audio/mp3" src="https://dl.faz2music.ir/download/3712434/Ahmad Solo - Shazdeh Pesar [128].mp3" id="urlchange"></audio>

This code replaces only one link

I want to be able to do the same for several links with the same ID or Class

Jquery


Solution

  • Using each and a class:

    $(document).ready(function() {
      $('#change').on('click', function(e) {
        const from = "dl.faz2music.ir";
        const to = "up.faz2music.ir";
        $(".urlchange").each(function() {
          if (this.matches("source")) {
            console.log()
            this.setAttribute("src", this.getAttribute("src").replace(from,to))
          }  
          else this.href = this.href.replace(from,to);
        });
        /*
        notice.showToast({
          text: 'Links converted',
          type: 'success',
          showClose: true
        });
        */
        alert("Links changed");
      });
      $("audio").on("mouseenter", (e) => console.log(e.target.querySelector("source").getAttribute("src")))
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
    <button type="button" id="change">Change</button>
    
    <a href="https://dl.faz2music.ir/download/3712434/Ahmad Solo - Shazdeh Pesar [320].mp3" class="urlchange">Download</a>
    <a href="https://dl.faz2music.ir/download/3712434/Ahmad Solo - Shazdeh Pesar [320].mp3" class="urlchange">Download</a>
    <a href="https://dl.faz2music.ir/download/3712434/Ahmad Solo - Shazdeh Pesar [320].mp3" class="urlchange">Download</a>
    <hr/>
    <audio controls><source type="audio/mp3" src="https://dl.faz2music.ir/download/3712434/Ahmad Solo - Shazdeh Pesar [320].mp3" class="urlchange"></audio><br/>
    <audio controls>Audio<source type="audio/mp3" src="https://dl.faz2music.ir/download/3712434/Ahmad Solo - Shazdeh Pesar [128].mp3" class="urlchange"></audio>