[英]Creating a DOM element from a complicated HTML-string
Is it possible to create a DOM from an HTML string that includes link, style, script and comments? 是否可以从包含链接,样式,脚本和注释的HTML字符串创建DOM ?
In my app, the end user will be pasting some form code, for example: 在我的应用程序中,最终用户将粘贴一些表单代码,例如:
<!-- Start comment -->
<link href="test.css" rel="stylesheet" type="text/css">
<style type="text/css">
#full_name{background:#fff; }
/* This is
another comment*/
</style>
<div>
<form action="process.php" method="post">
Full Name:<input type="text" name="full_name">
</form>
</div>
<script type='text/javascript' src='test.js'></script>
<!-- End comment -->
This is the jquery code: 这是jQuery代码:
$('#html-go').click(function (e) {
e.preventDefault();
var html_code = $('#html-code').val(),
obj = $('<div/>').html(html_code).contents();
alert(obj.attr("action"));
});
I want to load it into a DOM element for parsing but I get an undefined
error. 我想将其加载到DOM元素中进行解析,但出现undefined
错误。 If the form code contains only that between the tags, then everything's OK. 如果表单代码仅包含标签之间的代码,则一切正常。
Here's a JSFiddle that shows the error (paste the form code above). 这是显示错误的JSFiddle (粘贴上面的表单代码)。
$('#html-go').click(function (e)
{
e.preventDefault();
var html_code = $('#html-code').val();
console.log(html_code);
obj = $('<div/>').html(html_code).contents();
alert($(html_code).attr('action'));
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.