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

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.


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


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>

Tags:

Jquery