Wednesday, April 20, 2011

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?

From stackoverflow
  • 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.

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

0 comments:

Post a Comment