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

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

1

5 Answers

Take this HTML code:

<div>Hello World</div>

Doing:

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

Will result in:

<div>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.

1

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:

8

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

<div> <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> <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> <h1>H1 content</h1>
</div>

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!)

1

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:

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like