Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

jQuery .html() Get Containing Element

DZone's Guide to

jQuery .html() Get Containing Element

How to get all the contents of an HTML element in jQuery with a useful function.

· Web Dev Zone ·
Free Resource

Deploy code to production now. Release to users when ready. Learn how to separate code deployment from user-facing feature releases with LaunchDarkly.

Whenever you need to get all the contents of an 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.

Deploy code to production now. Release to users when ready. Learn how to separate code deployment from user-facing feature releases with LaunchDarkly.

Topics:
jquery ,web dev ,html ,tip

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}