[英]Why i'm getting just text instead of HTML using JQuery?
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.我有一个 H1 标签,我想在单击按钮时获取此元素的
HTML()
,但现在只获取文本而不是 HTML。 How can i get proper HTML?我怎样才能得到正确的 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
:你应该使用
outerHTML
:
The
outerHTML
attribute of the Element DOM interface gets the serialized HTML fragment describing the element including its descendants.Element DOM 接口的
outerHTML
属性获取描述元素及其后代的序列化 HTML 片段。 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 javascript中的
outerHTML
$(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()
.在
.html()
函数返回内部HTML元素,获得outerHTML
任何给定的元素,试图将其包装容器内,然后用得到他的HTML .html()
$(function(){
$('button').click(function(){
var elHTML = $('<div></div>').append($('h1'));
alert(elHTML.html());
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.