jQuery

jQuery .html() Get Containing Element

Whenever you need to get all the contents of a HTML element in jQuery you can use a handy function .html().

<div class="content">
  <h1>Headers</h1>
  <p>Paragraph of text</p>
</div>

<script>
    var contents = $('.content').html();
    alert(contents);
</script>

See the demo above for a demo of how to use the html() function. This will populate the contents variable with the contents of the .content div.

The problem I was having on a recent project is I needed to get the content of the HTML of a element but also needed to the parent element to which .html() does not include.

When you run the .html() function you will only get the contents of the element but it won't return the element itself. Then I discovered another function .wrap() allowing you wrap another HTML element around the one you have selected.

<div class="content">
  <h1>Headers</h1>
  <p>Paragraph of text</p>
</div>

<script>
    $('.content').wrap('<p/>');
</script>

The .content div is now wrapped around a paragraph tag, so if I was to call the .html function on the wraped paragraph tag it will return the entire content of the .content div including the .content div itself.

<div class="content">
  <h1>Headers</h1>
  <p>Paragraph of text</p>
</div>

<script>
    var contents = $('.content').wrap('<p/>').parent().html();
    alert(contents);
    $('.content').unwrap();
</script>

Now you can return the entire contents of an element including the parent object.

Back to top

Fastest WordPress Hosting With WPEngine

Stunning speed, powerful security, and best-in-class customer service. At WP Engine.

Risk free for 60 days