<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
<channel>
<title>Comments on snippet: 'JQuery plugin: Replace DOM element and keep classes and id'</title>
<link>http://snipplr.com</link>
<description>Snipplr comments feed'</description>
<language>en-us</language>
<pubDate>Sat, 25 May 2013 22:29:40 GMT</pubDate>
<item>
<title>xl-t said on 9/12/07</title>
<link>http://snipplr.com/view/1694/jquery-plugin-replace-dom-element-and-keep-classes-and-id/</link>
<description><![CDATA[ <p>In order to keep all attributes you might want to try this one:</p>

<pre><code>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();
    })
}
</code></pre>
 ]]></description>
<pubDate>Wed, 12 Sep 2007 07:18:35 GMT</pubDate>
<guid>http://snipplr.com/view/1694/jquery-plugin-replace-dom-element-and-keep-classes-and-id/</guid>
</item>
<item>
<title>jkline said on 7/20/07</title>
<link>http://snipplr.com/view/1694/jquery-plugin-replace-dom-element-and-keep-classes-and-id/</link>
<description><![CDATA[ <p>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</p>

<p>First I tried just doing this
          .attr('class', element.attr('class')).attr('id',element.attr('id'))</p>

<p>But I don't want an empty class or id attribute ending up in the result.</p>

<p>So I did this instead:</p>

<pre><code>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();
  });
};
</code></pre>

<p>Not as elegant and jQueryish, but more functional.</p>

<p>Thanks!</p>
 ]]></description>
<pubDate>Fri, 20 Jul 2007 17:43:53 GMT</pubDate>
<guid>http://snipplr.com/view/1694/jquery-plugin-replace-dom-element-and-keep-classes-and-id/</guid>
</item>
</channel>
</rss>