How do I replace a specific href link using Javascript?

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

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 ".store" from the url, but only this instance, not all urls in the page.

+3


source to share


2 answers


One way could be using 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>
      

Run codeHide result


+3


source


Check out 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>
      

Run codeHide result


sets x

to an array containing all the elements of a .

+2


source







All Articles