What's the difference between jQuery's replaceWith()
and html()
functions when HTML is being passed in as the parameter?
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
-1
and hopefully this will be helpful for all. :) –
Lp var $form = $target.closest('tr').replaceWith(html)
It turns out $form
contains the element before replacement. sigh –
Florous $('.pagination').replaceWith(new_pagination).hide();
was actually hiding the returned element, not the new one that I replaced it with. So instead of chaining hide(), I called it separately, right below calling replaceWith(). –
Cultigen 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>
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!)
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.
© 2022 - 2024 — McMap. All rights reserved.