Skip to main content

Get outer html of html element using Jquery

<div class='block'>
<p class='paragraph'> 
This is the text inside the second element

for an example if we consider above code block and write a code like below

var htmlString = $("#paragraph").html();

then htmString can have a value “This is the text inside the second element” only

now what if you want a result like “<p class=’paragraph’> This is the text inside the second element </p>”

Sometimes you will need the selected object as well, so below is a small jquery code block which will give you the complete html (outer html) of a Jquery selector.

There are 2 different ways for that, we will see both
There are two major methods used to get an objects outerHTML, we’ll be discussing both.

Getting wrapper html using the outerHTML method

var outer_element_html = $('jQuerySelector')[0].outerHTML ;

Just want to discuss 1 thing it will worked on latest browser only, if you are using 5 year old browser then may be it creates an issue

Get outer html of html element using Jquery clone method
using .clone method it will create an object copy into the memory. It will wrap into p tag around. After that we can use .html() function to get the inner html of the p tag. But if you are working with a big amount of data then cloning every element to the memory is not best way. See the below code for an example

outer_html = $('jQuerySelector').clone().wrap('<p>').parent().html();

in above code “jQuerySelector” is the selector we are using, you need to change it. If there are multiple items for selectors then you can go with .each loop and get the outerHtml of individual items.

Tarun Dudhatra

Tarun is a writer of website. He is a software professional with hands on 10+ years of experience. Generally he writes an article about microsoft technology, Javascript, SQL Server and JQuery. Here he shares his notes, experiences, examples.