skip to content

jQuery Snippets: replace

2 min read

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.

$('#myElem').before('<p>test</p>').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.

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

Using the previous example it would now look like this.

$('#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.

jQuery.fn.replace = function () {
  var stack = []
  return this.domManip(arguments, true, 1, function (a) {
    this.parentNode.replaceChild(a, this)
    stack.push(a)
  }).pushStack(stack)
}

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.

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