replace html attribute using jquery
-
30-04-2021 - |
Pergunta
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.
Nenhuma solução correta
Outras dicas
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.
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');