-2

I have this html

<div class="pic">
     <a class="shutterset_publication-workshop" title="" href="http://localhost/639.jpg">
    <img src="http://localhost/researchclub/yu.jpg" alt="copy-of-dsc03639">
     </a>
</div>

The problem is that i want to replace the 'href' attribute of the anchor tag using jquery while preserving the img element using jquery, but have failed.

$(".pic a['href']").replaceWith("<a>") is not working.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Dr Deo
  • 4,650
  • 11
  • 43
  • 73
  • 1
    "is not working" is not a description of the observed vs expected behaviour, "[I] [h]ave failed" is a lovely story, and there is no question about a programming language here. – Lightness Races in Orbit Feb 19 '12 at 16:54
  • Possible duplicate of [How to change the href for a hyperlink using jQuery](https://stackoverflow.com/questions/179713/how-to-change-the-href-for-a-hyperlink-using-jquery) – inetphantom Jul 11 '19 at 13:33

2 Answers2

2

The short version:

$("a.shutterset_publication-workshop").attr("href", "the new value");

or

$(".pic a.shutterset_publication-workshop").attr("href", "the new value");

or

$(".pic a").attr("href", "the new value");

The long version:

...but ave failed. $(".pic a['href']").replaceWith("<a>") is not working...

You're thinking in terms of markup. But the time the jQuery code is running, the markup is gone; instead, you have DOM elements (objects) in a tree structure in memory. You need to think in terms of finding the elements in the DOM (since you use jQuery, that would be with CSS selectors — and your selector was fine) and modifying their attributes/properties directly, not replacing them with new markup.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
2

Use the attr function to do this. There is no need to replace the element when you can modify it.

$(".pic a['href']").attr('href', 'http://google.com');
Evan Mulawski
  • 54,662
  • 15
  • 117
  • 144