[英]Why am I missing the outer div of my HTML block when I use JQuery's $.parseHTML?
When I parse an html string with $.parseHTML()
, the outer most div disappears. 当我使用$.parseHTML()
解析html字符串时,最外面的div消失了。
Given the html string: 给定html字符串:
var myCode = '<div class="outer">' +
' <div class="inner">' +
' <div>' +
' <p>Hello!</p>' +
' </div>' +
' <div>' +
' <p>Hello!!' +
' </p>' +
' </div>' +
' </div>' +
'</div>';
When I call parse this html, the outer most div ( class="outer"
) isn't present. 当我调用解析此html时,最外面的div( class="outer"
)不存在。
var $myHtmlObject = $($.parseHTML(myCode))
console.log($myHtmlObject.html()) // no "outer" div present.
I made a jsfiddle to show the behavior 我做了一个jsfiddle来显示行为
I can easily get around this by wrapping everything in another div
before I parse it, but that seems like a hack for something that should otherwise work. 我可以通过在解析之前将所有内容包装在另一个 div
来轻松解决此问题,但这似乎是对本应可以使用的东西的一种破解。
Because .html() gives the inner html of the first element of the set of element on which it was called. 因为.html()给出了被调用的元素集中的第一个元素的内部html。 What you are looking for here is the outerHTML
您在这里寻找的是outerHTML
console.log($myHtmlObject[0].outerHTML)
console.log($myHtmlObject.prop('outerHTML'))
Also there is no need to use parseHTML() in this case 同样在这种情况下也不需要使用parseHTML()
var log = (function() { var $log = $('#log'); return function(msg) { $('<p/>', { text: msg }).appendTo($log) } })(); var myCode = '<div class="outer">' + ' <div class="inner">' + ' <div>' + ' <p>Hello!</p>' + ' </div>' + ' <div>' + ' <p>Hello!!' + ' </p>' + ' </div>' + ' </div>' + '</div>'; var $html = $(myCode); log('html: ' + $html.html()) log('outer-html: ' + $html.prop('outerHTML'))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="log"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.