EN
jQuery - get outer html
8
points
Using jQuery it is possible to get outer HTML source code in the following ways.
1. jQuery prop
method example
// ONLINE-RUNNER:browser;
<html>
<head>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
</head>
<body>
<div id="element">
<h3>Head 1</h3>
<p>Some apostrophe text...</p>
<h3>Head 2</h3>
<p>Some apostrophe text...</p>
</div>
<script>
$(document).ready(function() {
var element = $('#element');
var html = element.prop('outerHTML');
console.log(html);
});
</script>
</body>
</html>
2. Element outerHTML
property
Example 1
// ONLINE-RUNNER:browser;
<html>
<head>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
</head>
<body>
<div id="element">
<h3>Head 1</h3>
<p>Some apostrophe text...</p>
<h3>Head 2</h3>
<p>Some apostrophe text...</p>
</div>
<script>
$(document).ready(function() {
var elements = $('#element');
var html = elements[0].outerHTML;
console.log(html);
});
</script>
</body>
</html>
Note:
- by using
elements[0]
first DOM element that has been found by jQuery is acessedelements[0]
is equal to result fromdocument.getElementById('element')
anddocument.querySelector('element')
method calls.
Example 2
// ONLINE-RUNNER:browser;
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<div class="element">
<h3>Head 1.1</h3>
<p>Some apostrophe text...</p>
<h3>Head 1.2</h3>
<p>Some apostrophe text...</p>
</div>
<div class="element">
<h3>Head 2.1</h3>
<p>Some apostrophe text...</p>
<h3>Head 2.2</h3>
<p>Some apostrophe text...</p>
</div>
<script>
$(document).ready(function() {
var elements = $('.element');
var html = '';
elements.each(function(index, element) {
html += element.outerHTML;
});
console.log(html);
});
</script>
</body>
</html>
Note:
element
represents pure DOM element object - without jQuery cover logic