SomethingAnd ...">

JQuery: replace text inside link?

I have the following html structure:

<div class="event tiny"> <a href="/whatever">Something</a> </div> 

And I want to replace the text this link with "Anything" ...

Wherein...

$('.event a').replaceWith("Anything");

... the text is replaced, but the link is gone.

Wherein...

$('.event a').text().replaceWith("Anything");

... Nothing happens.

+7
source share
4 answers

Similarly, if the new text is all the same.

 $('.event a').text("Anything"); 

jQuery navigates the elements of a and replaces its contents with the text "Anything" . "Anything"

+19
source

These guidelines for setting up inner text and url in a href did not work for me (using jQuery v1.8.3)

Here is what works:

HTML

  <a id="hrefAnalysisName" ></a> 

Javascript

 $("a#hrefAnalysisName").attr("href", "/SomePage/ShowAnalysisDetails.aspx"); $("a#hrefAnalysisName").text("Show analysis"); 

Hope this helps!

+4
source

You can also change the href link if it is associated with a URL.

 $('a[href="/whatever"]').text("Anything"); 
0
source

You can get this result, the following result will be the same:

HTML

 <div class="event tiny"> <a class="html" href="/whatever">Something</a></br> <a class="text" href="/whatever">Something</a></br> <a class="replaceWith" href="/whatever">Something</a> </div> 

Js

 $('.event a.html').html('Anything-html') $('.event a.text').text('Anything-text') $('.event a.replaceWith').replaceWith('<a class="replaceWith" href="/whatever">Anything-replaceWith</a>') 
0
source

All Articles