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.
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.
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.
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.
Use . replace() method on HTML element and replace it with the new HTML Document(eg.. $('html').
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With