JQuery plugin: Replace DOM element and keep classes and id


/ Published in: JavaScript
Save to your folder(s)

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


Copy this code and paste it in your HTML
  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

You need to login to post a comment.