Wednesday 4 February 2015

jQuery - How to get Html including the selector?

As you know jQuery .html() method can be used to get the HTML contents of the first element in the set of matched elements. But sometimes you might want to get the HTML including the container as well.

For example if you have below html

<div id="container">
 <div id="content">jQuery is awesome</div>
</div>

and if you use $('#container').html() it will give you

<div id="content">jQuery is awesome</div>
i.e. it returns the "innerHTML" of the "container" DIV.

There are many workarounds to it i.e. to get html including the "container".

Using wrap()

If you wrap the container in a dummy P tag you will get the container HTML as well.

var outerHtml  = $('#container').wrap('<p/>').parent().html();
Using clone()
var outerHtml = $("<div />").append($('#container').clone()).html();

Using wrap actually affects the DOM tree displayed to the user. This doesn't.

No comments:

Post a Comment