get outerhtml with javascript

How to Get Element’s Outer HTML using jQuery

Outer HTML is the HTML of an element including the element itself while inner HTML is the HTML of the contents of the element. Often you may need to get an element’s outer HTML. In this article, we will learn how to get outer HTML of element. Unfortunately, there is no direct method in jQuery to get element’s outer HTML so we will get it using some round about methods. We will also learn how to do this using plain JavaScript. They are all very easy and just take a single line of code.

How to Get Element’s Outer HTML using jQuery

Let us say you have the following HTML element.

<div id='myDiv' class='myClass'>

Here are the different ways to get the outer HTML of above element. We are basically using jQuery to get the element using selectors but we are using outerHTML property available for each element.

// Gets DOM element excluding the element itself. That is, inner HTML

// Gives you outer HTML as well but only for the first element

// Gives you the outer HTML for all the selected elements
var html = '';
$('.myDiv').each(function () {
    html += this.outerHTML;

//Or if you need a one liner for the previous code
$('.myDiv').get().map(function(v){return v.outerHTML}).join('');

In this article, we have learnt how to get element’s outer HTML. Since jQuery does not have a readymade function to get outerHTML, we simply use outerHTML property available in JavaScript.

Also read:

How to Get Image Size & Width Using JavaScript
How to Use Multiple jQuery Versions on Same Page
How to Convert Form Data to JS Object Using jQuery
How to Detect Mobile Device Using jQuery
How to Bind Event to Dynamic Element in jQuery

Leave a Reply

Your email address will not be published. Required fields are marked *