javascript 使用js从div获取原始HTML?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3580447/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 01:36:22  来源:igfitidea点击:

Get raw HTML from a div using js?

javascriptjquery

提问by Cyber Junkie

I'm working on a website where users can create and save their own HTML forms. Instead of inserting form elements and ids one by one in the database I was thinking to use js (preferably jquery) to just get the form's HTML (in code source format) and insert it in a text row via mysql.

我正在开发一个网站,用户可以在其中创建和保存自己的 HTML 表单。我没有在数据库中一个一个地插入表单元素和 id,我想使用 js(最好是 jquery)来获取表单的 HTML(以代码源格式)并通过 mysql 将其插入到文本行中。

For example I have a form in a div

例如,我在 div 中有一个表单

<div class="new_form">
<form>
Your Name:
<input type="text" name="something" />
About You:
<textarea name=about_you></textarea>
</form>
</div>

With js is it possible to get the raw HTML within the "new_form" div?

使用 js 是否可以在“new_form”div 中获取原始 HTML?

回答by BrunoLM

To get all HTML inside the div

获取 div 中的所有 HTML

$(".new_form").html()

To get only the text it would be

要仅获取文本,它将是

$(".new_form").text()

You might need to validate the HTML, this questionmight help you (it's in C# but you can get the idea)

您可能需要验证 HTML,这个问题可能对您有所帮助(它在 C# 中,但您可以理解)

回答by bobince

Note when you use innerHTMLor html()as above you won't get the exactraw HTML you put in. You'll get the web browser's idea of what the current document objects should look like serialised into HTML.

请注意,当您使用innerHTMLhtml()如上所述时,您将无法获得您放入的确切原始 HTML。您将获得 Web 浏览器关于当前文档对象序列化为 HTML 应该是什么样子的想法。

There will be browser differences in the exact format that comes out, in areas like name case, spacing, attribute order, which characters are &-escaped, and attribute quoting. IE, in particular, can give you invalid HTML where attributes that should be quoted aren't. IE will also, incorrectly, output the current values of form fields in their valueattributes.

在出现的确切格式方面,浏览器会有所不同,例如名称大小写、间距、属性顺序、&转义字符和属性引用等方面。尤其是 IE,它可以为您提供无效的 HTML,其中应该引用的属性不是。IE 还会错误地在其value属性中输出表单字段的当前值。

You should also be aware of the cross-site-scripting risks involved in letting users submit arbitrary HTML. If you are to make this safe you will need some heavy duty HTML ‘purification'.

您还应该了解让用户提交任意 HTML 所涉及的跨站点脚本风险。如果您要确保安全,您将需要一些重型 HTML '净化'。

回答by Hammerite

Yes, it is. You use the innerHTML property of the div. Like this:

是的。您使用 div 的 innerHTML 属性。像这样:

var myHTML = document.getElementById('new_form').innerHTML;