Get outerHTML of an element with JavaScript/jQuery
This post will discuss how to get outerHTML of an element in JavaScript and jQuery.
The outerHTML is often used to replace the element and its contents completely. It differs from the innerHTML as innerHTML only represent the HTML of contents of an element, while outerHTML includes the HTML of element itself with its descendants.
1. Using JavaScript
In JavaScript, you can easily get the value of an element’s outerHTML with the outerHTML attribute.
JS
|
1 2 |
var element = document.getElementById("cc"); console.log(element.outerHTML); |
HTML
|
1 2 3 |
<div id="cc"> <p>Content</p> </div> |
2. Using jQuery
With jQuery, you can access the outerHTML attribute of HTML using the $(selector).prop() or $(selector).attr() method.
JS
|
1 2 3 4 |
$(document).ready(function() { var outerHTML = $("#cc").prop("outerHTML"); console.log(outerHTML); }); |
HTML
|
1 2 3 |
<div id="cc"> <p>Content</p> </div> |
Alternatively, you can access the underlying HTML of the object returned by the $(selector) and get its .outerHTML property.
JS
|
1 2 3 4 |
$(document).ready(function() { var outerHTML = $("#cc")[0].outerHTML; console.log(outerHTML); }); |
HTML
|
1 2 3 |
<div id="cc"> <p>Content</p> </div> |
That’s all about getting outerHTML of an element in JavaScript and jQuery.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)