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 application' );

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 application' );    }    else { 	   // do nothing    } });

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: