Posted By

gaunab on 11/20/06


Tagged

jquery


Versions (?)

Who likes this?

6 people have marked this snippet as a favorite

bartekk
francisre
vali29
heinz1959
suzt808
malachaifrazier


JQuery plugin: Replace DOM element and keep classes and id


 / Published in: JavaScript
 

Replaces a DOM Element with another, but keeps the classes and IDs of the old one.

  1. jQuery.fn.replaceWith = function(replacement) {
  2. return this.each(function(){
  3. element = $(this);
  4. $(this)
  5. .after(replacement).next()
  6. .attr('class', element.attr('class')).attr('id',element.attr('id'))
  7. .html(element.html())
  8. .prev().remove();
  9. });
  10. };
  11.  
  12. /*
  13. usage example
  14.  
  15. $('a#fooid').replaceWith('<span></span>');
  16.  
  17. before:
  18. <a id="fooid" class="whatever">some text</a>
  19.  
  20. after:
  21. <span id="fooid" class="whatever">some text</span>
  22.  
  23. */

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: jkline on July 20, 2007

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:

jQuery.fn.replaceWith = function(replacement) {
  return this.each(function(){
    element = $(this);
    $(this)
      .after(replacement).next()
      .html(element.html());

   if (element.attr('class')) {
    element.next().attr('class', element.attr('class'));
   }

   if (element.attr('id')) {
    element.next().attr('id',element.attr('id'));
   }

   element.remove();
  });
};

Not as elegant and jQueryish, but more functional.

Thanks!

Posted By: xl-t on September 12, 2007

In order to keep all attributes you might want to try this one:

jQuery.fn.replaceWith = function(replacement) 
{
    return this.each (function() 
    {
        element = $(this);
        $(this).after(replacement).next().html(element.html());
        for (var i = 0; i < this.attributes.length; i++) {
            element.next().attr(this.attributes[i].nodeName, this.attributes[i].nodeValue);
        }
        element.remove();
    })
}

You need to login to post a comment.