Search code examples
javascripthyperlinkurl-rewritinghrefdom-events

Modify some href links on a page using Javascript


I would like to change every link on my page held by the class .btn_view

My links on my page are like :

<a class="btn_view" href="/download/documentA.pdf">VIEW</a>
<a class="btn_view" href="/download/documentB.pdf">VIEW</a>
<a class="btn_view" href="/download/documentC.pdf">VIEW</a>
...

into

<a class="btn_view" href="viewer.html?file=/download/documentA.pdf">VIEW</a>
<a class="btn_view" href="viewer.html?file=/download/documentB.pdf">VIEW</a>
<a class="btn_view" href="viewer.html?file=/download/documentC.pdf">VIEW</a>
...

I am working on this piece of code, but I can't figure out the issues :

const items = document.getElementsByClassName(".btn_view");

items.addEventListener('click', (e) => {
  for (var i = 0; i < items.length; i++) //Loop through your elements
    {
        //Verify that the href starts with /download/
        if (items[i].href.indexOf("/download/") === 0)
        {
            // add viewer link in front of original url
            items[i].href = "viewer.html?file=" + items[i].href
            //If it does, open that URL in a new window.
            window.open(items[i].href, "_blank");
        }
    }
});

Solution

  • Why are you changing on events just loop through and change it here is how .

    function modifyLink(){
    var items = document.getElementsByClassName("btn_view");
    for(var i=0;i<items.length;i++){
     let href = items[i].getAttribute("href");
     console.log(href);
     items[i].setAttribute('href','viewer.html?file='+href);
     
    }
    for(var i=0;i<items.length;i++){
     console.log(items[i].getAttribute("href"));
    }
    }
    
    modifyLink();
    <a class="btn_view" href="/download/documentA.pdf">VIEW</a>
    <a class="btn_view" href="/download/documentB.pdf">VIEW</a>
    <a class="btn_view" href="/download/documentC.pdf">VIEW</a>