Rookie
Rookie

Reputation: 83

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.

Upvotes: 8

Views: 14107

Answers (2)

ikrabbe
ikrabbe

Reputation: 1929

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.

Upvotes: 8

Arun P Johny
Arun P Johny

Reputation: 388446

One way could be is to use the href value to find the anchor

var a = document.querySelector('a[href="http://www.this.link.co.nz"]');
if (a) {
  a.setAttribute('href', 'http://www.that.link.co.nz')
}
<a href="http://www.this.link.co.nz" title="this link">
  <img src="/filename.jpg" />
</a>

Upvotes: 6

Related Questions