jQuery Snippets: replace

Sometimes you just need to replace one element with another. Of course jQuery makes this easy! You might run this chain to replace one or more elements with a new one.

  1. $('#myElem')
  2.     .before('<p>test</p>')
  3.     .remove();

This chain simply inserts a <p> tag before the selected element and then removes that element resulting in a replacement. You could also achieve the same results by using the after method instead of before.

As nice as that is, I would still prefer to have something a little more explicit and something shorter! So here is a true replace method.

  1. jQuery.fn.replace = function() {
  2.     return this.domManip(arguments, true, 1, function(a){
  3.         this.parentNode.replaceChild( a, this );
  4.     });
  5. };

Using the previous example it would now look like this.

  1. $('#myElem').replace('<p>test</p>');

I just have one problem with this, and it is about semantics. The element in the jQuery object is still '#myElem'. This is normal behavior for jQuery methods like append and remove. However, since this method is called replace, shouldn't the element in the jQuery object be replaced also? I think so! Here is a revised replace method that also updates the jQuery object with the new elements.

  1. jQuery.fn.replace = function() {
  2.     var stack = [];
  3.     return this.domManip(arguments, true, 1, function(a){
  4.         this.parentNode.replaceChild( a, this );
  5.         stack.push(a);
  6.     }).pushStack( stack );
  7. };

Now this method can be used to replace an element and then work with the replacement. So we could replace '#myElem' as previously but now also bind a click event to the <p> like this.

  1. $('#myElem')
  2.     .replace('<p>test</p>')
  3.     .bind('click' doSomething);

It should be noted that just like with append you can pass replace a string of HTML, an actual element or a jQuery object. You can download the source code and see an example here.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>