EN
jQuery - get outer html
8 points
Using jQuery it is possible to get outer HTML source code in the following ways.
xxxxxxxxxx
1
<html>
2
<head>
3
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
4
</head>
5
<body>
6
<div id="element">
7
<h3>Head 1</h3>
8
<p>Some apostrophe text...</p>
9
<h3>Head 2</h3>
10
<p>Some apostrophe text...</p>
11
</div>
12
<script>
13
14
$(document).ready(function() {
15
var element = $('#element');
16
var html = element.prop('outerHTML');
17
18
console.log(html);
19
});
20
21
</script>
22
</body>
23
</html>
xxxxxxxxxx
1
<html>
2
<head>
3
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
4
</head>
5
<body>
6
<div id="element">
7
<h3>Head 1</h3>
8
<p>Some apostrophe text...</p>
9
<h3>Head 2</h3>
10
<p>Some apostrophe text...</p>
11
</div>
12
<script>
13
14
$(document).ready(function() {
15
var elements = $('#element');
16
var html = elements[0].outerHTML;
17
18
console.log(html);
19
});
20
21
</script>
22
</body>
23
</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.
xxxxxxxxxx
1
<html>
2
<head>
3
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
4
</head>
5
<body>
6
<div class="element">
7
<h3>Head 1.1</h3>
8
<p>Some apostrophe text...</p>
9
<h3>Head 1.2</h3>
10
<p>Some apostrophe text...</p>
11
</div>
12
<div class="element">
13
<h3>Head 2.1</h3>
14
<p>Some apostrophe text...</p>
15
<h3>Head 2.2</h3>
16
<p>Some apostrophe text...</p>
17
</div>
18
<script>
19
20
$(document).ready(function() {
21
var elements = $('.element');
22
23
var html = '';
24
25
elements.each(function(index, element) {
26
html += element.outerHTML;
27
});
28
29
console.log(html);
30
});
31
32
</script>
33
</body>
34
</html>
Note:
element
represents pure DOM element object - without jQuery cover logic