jQuery replaceWith

Let’s say you have a bunch of elements that under certain situations you want to replace with another element. jQuery’s replaceWith() function is perfect for that.

Here is an example of replacing all links with the class replace with a different link. The use case was finding certain buttons that say “Apply Now” and replacing them with buttons that say “Finish your application”. Since searching for “Apply Now” wasn’t perfect (the text and other links said it, too) I manually put in the replace class so I knew exactly which elements I’d be selecting.

$( "a.replace" ).replaceWith( '"/application/" class="button arrow-right">Finish your applicationArchived Link' );

Want to perform this action if a cookie exists? Try using js-cookie:

$( document ).ready(function() {    if (Cookies.get('cookiename')) {    	$( "a.replace" ).replaceWith( '"/application/" class="button arrow-right">Finish your applicationArchived Link' );    }    else { 	   // do nothing    } });


Comments

Leave a Reply

Webmentions

If you've written a response on your own site, you can enter that post's URL to reply with a Webmention.

The only requirement for your mention to be recognized is a link to this post in your post's content. You can update or delete your post and then re-submit the URL in the form to update or remove your response from this page.

Learn more about Webmentions.