Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It happens because your element does not have a parent. Append it to the DOM or to another jQuery collection and it will work.</p> <p>I created a <a href="http://jsfiddle.net/sTcz2/" rel="nofollow">little demo</a> that might help in understanding what this method does.</p> <p><strong>DETAILS:</strong></p> <p>I will sum up the research that is detailed in the comments below this answer. Thanks to PSL, calberts, Jason P and A. Wolff.</p> <ol> <li><p>The <a href="http://api.jquery.com/replaceWith/" rel="nofollow">documentation of <code>replaceWith</code></a> states the following:</p> <blockquote> <p>As of jQuery 1.4, .replaceWith() can also work on disconnected DOM nodes. For example, with the following code, .replaceWith() returns a jQuery set containing only a paragraph.: </p> <p><code>$( "&lt;div/&gt;" ).replaceWith("&lt;p&gt;&lt;/p&gt;" );</code></p> </blockquote></li> <li><p>This means that the example provided by the OP should indeed work. <a href="http://jsfiddle.net/my89M/9/" rel="nofollow">And it works till version 1.8</a>. Unfortunately, <a href="http://jsfiddle.net/my89M/10/" rel="nofollow">from version 1.9 it stops working</a>. This seemed to be a bug and only happens if you are trying to replace the "root element" of the jQuery object.</p></li> <li><p>Actually <a href="http://jquery.com/upgrade-guide/1.9/#after-before-and-replacewith-with-disconnected-nodes" rel="nofollow">the change in 1.9 was documented</a>:</p> <blockquote> <p>Prior to 1.9, .after(), .before(), and .replaceWith() would attempt to add or change nodes in the current jQuery set if the first node in the set was not connected to a document, and in those cases return a new jQuery set rather than the original set. This created several inconsistencies and outright bugs--the method might or might not return a new result depending on its arguments! As of 1.9, these methods always return the original unmodified set and attempting to use .after(), .before(), or .replaceWith() on a node without a parent has no effect--that is, neither the set or the nodes it contains are changed.</p> </blockquote> <p>Problem is that the change never made it to the official docs. I found <a href="http://bugs.jquery.com/ticket/13338" rel="nofollow">a bug</a> posted about this, but it was closed because it belongs to a different tracker.</p></li> </ol> <hr> <p>Quick Solution:</p> <p>In the OP's situation, the easiest way to "replace" the element would be</p> <pre><code>var obj = $('&lt;div id="obj"&gt;Text&lt;/div&gt;'); obj = $('&lt;span&gt;New text&lt;/span&gt;'); </code></pre> <p>but only if it is not in the DOM yet :).</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload