Search code examples
javascripthtmlhref

Add text from a variable to href link inside actor tag


I have 15 actor tags with href links like this

    <a href="https://www.w3schools.com/temp.pdf"></a>

As these PDF's are updated frequently and I don't want to cache them browser, I thought of adding updated Date at the end of this href link as ?date=updateDate by storing the updateDate in a variable like

    <script>
        updateDate = "20210624";
    </script>

I thought of updating my href link as it might add date to the url at the end

    <a href="https://www.w3schools.com/temp.pdf?date="+updateDate></a>

But it is not working. I did my research on this and got to know that I need to update the url seperately for each of the 15 links. Is there any way that I can do it in the way I can store the date value and use it for all 15 links without changing everyone?


Solution

  • Try this:

    document.querySelectorAll('a').forEach(e => {
      e.href += new Date().getTime();
    })
    <a href='https://www.w3schools.com/temp.pdf?date='>link</a>
    <a href='https://www.w3schools.com/temp.pdf?date='>link</a>
    <a href='https://www.w3schools.com/temp.pdf?date='>link</a>

    If you want to only change the href of certain anchor tags, assign them a class name:

    document.querySelectorAll('a.nocache').forEach(e => {
      e.href += new Date().getTime();
    })
    <a class="nocache" href='https://www.w3schools.com/temp.pdf?date='>link</a>
    <a href='https://www.w3schools.com/temp.pdf'>link</a>
    <a class="nocache" href='https://www.w3schools.com/temp.pdf?date='>link</a>