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

Try RAD Studio for FREE!  It’s the fastest way to develop cross-platform Native Apps with flexible Cloud services and broad IoT connectivity. Start Your Trial Today!

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.

Get Your Apps to Customers 5X Faster with RAD Studio. Brought to you in partnership with Embarcadero.

Topics:
jquery ,web dev ,html ,tip

Published at DZone with permission of Paul Underwood, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}