Sebi2020
Sebi2020

Reputation: 2150

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

Example 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):

And not the correct form:

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

Also see this fiddle: https://jsfiddle.net/m1fqzLv6/

For now I did not found any javascript function which would allow this.

Upvotes: 0

Views: 534

Answers (1)

BurninLeo
BurninLeo

Reputation: 4464

This question is based on the assumption that document.createElement() would produce HTML code. This is incorrect.

Actually, the HTML code is parsed into a document object model (DOM). JavaScript can subsequently modify the DOM (also see comments from T.J. Crowder above). In your example, an <input> element is added.

Chrome, in its developer tool, represent the DOM by HTML code that most developers can easily read. And if there is an <input> element in the DOM, the devtools panel has to decide how to represent it. Apparently, it chooses the long form with <input></input>. This, however is only an output decision.

Upvotes: 2

Related Questions