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

Make the transition to Node.js if you are a Java, PHP, Rails or .NET developer with these resources to help jumpstart your Node.js knowledge plus pick up some development tips.  Brought to you in partnership with IBM.

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.

Learn why developers are gravitating towards Node and its ability to retain and leverage the skills of JavaScript developers and the ability to deliver projects faster than other languages can.  Brought to you in partnership with IBM.

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 best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

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

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

{{ parent.tldr }}

{{ parent.urlSource.name }}