jQuery Snippets: replace
Friday, June 1, 2007
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);
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.
Posted in jQuery with 2 comments
I just wanted to thank you for this method. I didn’t want to have to mess with regular expressions to replace one <h1> tag with another, and this worked perfectly.
In case you’re curious, I replaced
with the less-semantic but easier-to-style-nicely
Thanks again!
By Kerrick on Thursday, June 11, 2009 at 01:47 PM
Thanks Kerrick!
BTW … in later versions of jQuery this method is now in the core. It is called
replaceWithinstead ofreplace. Here are the docs: http://docs.jquery.com/Manipulation/replaceWithBy Brandon Aaron on Thursday, June 11, 2009 at 01:57 PM