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

Learn how error monitoring with Sentry closes the gap between the product team and your customers. With Sentry, you can focus on what you do best: building and scaling software that makes your users’ lives better.

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.

What’s the best way to boost the efficiency of your product team and ship with confidence? Check out this ebook to learn how Sentry's real-time error monitoring helps developers stay in their workflow to fix bugs before the user even knows there’s a problem.

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 }}