简体   繁体   English

为什么 `document.createElement` 不允许创建自闭合标签?

[英]Why does `document.createElement` do not allow the creation of self-closing tags?

Example JavaScript示例 JavaScript

<html>
<body>
<form id="test"></form>
</body>
</html>
let input_el = document.createElement('input');
input_el.setAttribute('type','text');
input_el.setAttribute('name','your_name');
let my_form = document.getElementById('test');
my_form.prepend(input_el);

Produces the following output in the chrome developer tools on windows (chrome version 96.0.4664.45):在 windows(chrome 版本 96.0.4664.45)上的 chrome 开发人员工具中生成以下 output:

And not the correct form:而不是正确的形式:

<input type="text" name="your_name">

Also see this fiddle: https://jsfiddle.net/m1fqzLv6/另见这个小提琴: https://jsfiddle.net/m1fqzLv6/

For now I did not found any javascript function which would allow this.目前我没有找到任何允许这样做的 javascript function。

This question is based on the assumption that document.createElement() would produce HTML code.这个问题是基于document.createElement()会产生 HTML 代码的假设。 This is incorrect.这是不正确的。

Actually, the HTML code is parsed into a document object model (DOM).实际上,HTML 代码被解析成文档 object model (DOM)。 JavaScript can subsequently modify the DOM (also see comments from TJ Crowder above). JavaScript 可以随后修改 DOM(另见上面 TJ Crowder 的评论)。 In your example, an <input> element is added.在您的示例中,添加了一个<input>元素。

Chrome, in its developer tool, represent the DOM by HTML code that most developers can easily read. Chrome 在其开发者工具中,通过 HTML 代码表示 DOM,大多数开发者都可以轻松阅读。 And if there is an <input> element in the DOM, the devtools panel has to decide how to represent it.如果 DOM 中有<input>元素,则开发工具面板必须决定如何表示它。 Apparently, it chooses the long form with <input></input> .显然,它选择带有<input></input>的长格式。 This, however is only an output decision.然而,这只是 output 决定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM