I have a H1 tag & i want to get HTML()
of this element on button click but right now getting just text instead of HTML. How can i get proper HTML?
My Code:-
$(function(){ $('button').click(function(){ alert($('h1').html()); }); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <h1 style="color:indianRed">Heading 1</h1> <button>Click</button>
You should use outerHTML
:
The
outerHTML
attribute of the Element DOM interface gets the serialized HTML fragment describing the element including its descendants. It can also be set to replace the element with nodes parsed from the given string.
$(function(){ $('button').click(function(){ alert($('h1').get(0).outerHTML); }); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <h1 style="color:indianRed">Heading 1</h1> <button>Click</button>
outerHTML
in javascript
$(function(){ $('button').click(function(){ alert(document.querySelector("h1").outerHTML); }); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <h1 style="color:indianRed">Heading 1</h1> <button>Click</button>
The .html()
function return the inner html of an element, to get the outerHTML
of any given element, try to wrap it inside a container then get his html using .html()
.
$(function(){
$('button').click(function(){
var elHTML = $('<div></div>').append($('h1'));
alert(elHTML.html());
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.