Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace a specific href link using Javascript?

I'll try again with this as I'm not sure the last time I put a very clear question... I have a page that has a lot of linked images. I would like to change just one of the image links (it's the logo) using javascript. I can not directly edit the "body" html, but can put js in the "head" region.

Here is the html code:

<div id="ctl00">
  <h1 class="logo">
  <a href="http://www.store.domain.co.nz" title="Menswear"><img src="/user/files/logo.png title="Menswear" alt="Menswear"></a>
  </h1>
</div>

and I want to change the html to:

<div id="ctl00">
    <h1 class="logo">
<a href="http://www.domain.co.nz" title="Menswear"><img src="/user/files/logo.png title="Menswear" alt="Menswear"></a>
</h1>
</div>

Basically I want to remove the ".store" from the URL, but only this instance, not all URLs on the page.

like image 298
Rookie Avatar asked Dec 14 '22 13:12

Rookie


1 Answers

Check the DOM functions:

var x = document.getElementsByTagName("a")
for (i=0;i<x.length;++i) {
  if (x[i].getAttribute("href") == "http://www.this.link.co.nz") {
    x[i].setAttribute("href", "http://www.that.link.co.nz")
    x[i].setAttribute("title", "that link")
    x[i].replaceChild(
      document.createTextNode(
        "changed img:filename.jpg"
      ),
      x[i].firstChild
    )
  }
}
<p><a href="http://www.this.link.co.nz" title="this link">
    img:filename.jpg
</a>
</p>
<p><a href="http://www.this.link.co.nz" title="this link">
    img:filename.jpg
</a>
</p>

sets x to an array containing all a elements.

like image 66
ikrabbe Avatar answered Dec 17 '22 02:12

ikrabbe