Use jQuery to get the HTML of a container, including the container itself

Problem: You have the following markup, and you'd like to use jQuery to retrieve the contents of #container, but also include #container's markup in the returned HTML:

<div id="container">
  <div class="foo">bar</div>
</div>

There are a number of ways to tackle the problem, but the most elegant solution I've come across is one posted as an answer to a question on Stack Overflow. This following snippet selects the container and wraps it in a <div> tag. It then immediately selects the wrapping tag with parent(), before assigning its contents to x.

var x = $('#container').wrap('

').parent().html();

If you like, you can remove the wrapping <div> tag:

$('#container').unwrap();