What's the difference between jQuery's replaceWith() and html()?

JqueryReplacewith

Jquery Problem Overview


What's the difference between jQuery's replaceWith() and html() functions when HTML is being passed in as the parameter?

Jquery Solutions


Solution 1 - Jquery

Take this HTML code:

<div id="mydiv">Hello World</div>

Doing:

$('#mydiv').html('Aloha World');

Will result in:

<div id="mydiv">Aloha World</div>

Doing:

$('#mydiv').replaceWith('Aloha World');

Will result in:

Aloha World

So html() replaces the contents of the element, while replaceWith() replaces the actual element.

Solution 2 - Jquery

replaceWith() will replace the current element, whereas html() simply replaces the contents.

Note that the replaceWith() will not actually delete the element but simply remove it from the DOM and return it to you in the collection.

An example for Peter: http://jsbin.com/ofirip/2

Solution 3 - Jquery

There are two ways of using html() and replaceWith() Jquery functions.

<div id="test_id">
   <p>My Content</p>
</div>

1.) html() vs replaceWith()

var html = $('#test_id p').html(); will return the "My Content"

But the var replaceWith = $('#test_id p').replaceWith(); will return the whole DOM object of <p>My Content</p>.


2.) html('value') vs replaceWith('value')

$('#test_id p').html('<h1>H1 content</h1>'); will give you the following out put.

<div id="test_id">
  <p><h1>H1 content</h1></p>
</div>

But the $('#test_id p').replaceWith('<h1>H1 content</h1>'); will give you the following out put.

<div id="test_id">
      <h1>H1 content</h1>
</div>

Solution 4 - Jquery

Old question but this may help someone.

There are some differences in how these functions operate in Internet Explorer and Chrome / Firefox IF your HTML is not valid.

Clean up your HTML and they'll work as documented.

(Not closing my </center> cost me my evening!)

Solution 5 - Jquery

It may also be useful to know that .empty().append() can also be used instead of .html(). In the benchmark shown below this is faster but only if you need to call this function many times.

See: https://jsperf.com/jquery-html-vs-empty-append-test

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDMCSView Question on Stackoverflow
Solution 1 - JqueryPaolo BergantinoView Answer on Stackoverflow
Solution 2 - JquerycgpView Answer on Stackoverflow
Solution 3 - JqueryHarshaView Answer on Stackoverflow
Solution 4 - JqueryBenjamin WoottonView Answer on Stackoverflow
Solution 5 - JquerymistajollyView Answer on Stackoverflow