/ Published in: JavaScript
Replaces a DOM Element with another, but keeps the classes and IDs of the old one.
Expand |
Embed | Plain Text
jQuery.fn.replaceWith = function(replacement) { return this.each(function(){ element = $(this); $(this) .after(replacement).next() .attr('class', element.attr('class')).attr('id',element.attr('id')) .html(element.html()) .prev().remove(); }); }; /* usage example $('a#fooid').replaceWith('<span></span>'); before: <a id="fooid" class="whatever">some text</a> after: <span id="fooid" class="whatever">some text</span> */
Comments
Subscribe to comments
You need to login to post a comment.

I tried that and it barfed if the element I was trying to replace did not have any class. The error was $(this).after(replacement).next().attr("class", element.attr("class")) has no properties at jquery.replacewith.js Line 13
First I tried just doing this .attr('class', element.attr('class')).attr('id',element.attr('id'))
But I don't want an empty class or id attribute ending up in the result.
So I did this instead:
Not as elegant and jQueryish, but more functional.
Thanks!
In order to keep all attributes you might want to try this one: