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'> ... </div>
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 $('.myDiv').html() // Gives you outer HTML as well but only for the first element $('.myDiv')[0].outerHTML // 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
Related posts:
How to Check if Browser Tab is Active
How to Select Element By Text in JavaScript
How to Smooth Scroll on Clicking Links
How to Match Exact String in JavaScript
How to Persist Variables Between Page Load
How to Use JavaScript Variables in jQuery Selectors
How to Remove All Child Elements of DOM Node in JS
How to Find Sum of Array of Numbers in JavaScript

Sreeram has more than 10 years of experience in web development, Python, Linux, SQL and database programming.