Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: replace text inside link? [duplicate]

I have the following html structure:

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

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

When doing this …

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

… the text is replaced but also the link is gone.

When doing this … 

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

… nothing happens.

like image 912
matt Avatar asked Sep 30 '12 17:09

matt


People also ask

How do I change the text of a link in jQuery?

Answer: Use the jQuery . attr() Method You can use the jQuery . attr() method to dynamically set or change the value of href attribute of a link or anchor tag. This method can also be used to get the value of any attribute.

How do I change a href text?

Change an existing hyperlinkRight-click anywhere on the link and, on the shortcut menu, click Edit Hyperlink. In the Edit Hyperlink dialog, select the text in the Text to display box.

How to use replaceWith in jQuery?

The replaceWith() method in jQuery is used to replace the selected elements with the new one. This method replaces the matched elements with the specified HTML elements. It returns the replaced elements. This method is similar to the replaceAll() method.

How do you replace content in HTML?

Use . replace() method on HTML element and replace it with the new HTML Document(eg.. $('html').


1 Answers

Like this, if the new text is all the same.

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

jQuery loops over the a elements, and replaces its content with the "Anything" text.

like image 58
I Hate Lazy Avatar answered Dec 04 '22 19:12

I Hate Lazy