jQuery replaceWith

July 18, 2016
Category: TIL
Tags: Javascript

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( '<a href=\"/application/\" class=\"button arrow-right\">Finish your application</a>' );

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

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

Find this post useful?

Buy me a coffeeBuy me a coffee