简体   繁体   English

我可以在任何HTML元素上调用appendChild吗?

[英]Can I call appendChild on any HTML element?

Does anybody know if I can call appendChild on any HTML element ? 有人知道我是否可以在任何HTML元素上调用appendChild吗?

Specifically I need to do it on input type='text' and it seems to work ? 具体来说,我需要在输入type ='text'上执行此操作,这似乎可行吗? but is this correct ? 但这是正确的吗?

Below a snippet of my code: 下面是我的代码片段:

var txt = document.createElement('input');
txt.type = 'text';
...
var div = document.createElement('div');
...
txt.appendChild(div);

Does anybody know if I can call appendChild on any HTML element ? 有人知道我是否可以在任何HTML元素上调用appendChild吗?

You can. 您可以。 It is a standard feature of an element node. 它是元素节点的标准功能。 It might not always make sense though. 但是,这可能并不总是很有意义。

Specifically I need to do it on input type='text' and it seems to work ? 具体来说,我需要在输入type ='text'上执行此操作,这似乎可行吗? but is this correct ? 但这是正确的吗?

<input> elements are defined as empty. <input>元素定义为空。 They still have standard DOM methods on them, but they aren't allowed to have child nodes. 它们仍然具有标准的DOM方法,但不允许其具有子节点。 You are attempting to put the DOM into an invalid state, and (as far as I know) the behaviour for what happens when you do is undefined. 您正在尝试将DOM置于无效状态,并且(据我所知)您执行操作时所发生的行为是不确定的。 You should not do this. 您不应该这样做。

From the w3.org on input element : w3.org的输入元素开始

Content model: Empty. 内容模型:空。

It's invalid to put an element inside an input . 将元素放在input是无效的。

If you want to set the value of the input, use the value property : 如果要设置输入的value ,请使用value属性:

input.value = 'someText';

If what you want is to add an element before your input, use insertBefore : 如果要在输入之前添加元素,请使用insertBefore

input.parentNode.insertBefore(div, input);

To insert the div after your input, you would do 要在输入后插入div,您可以

input.parentNode.insertBefore(div, input.nextSibling);

No you cannot append a child to an input element. 不可以,您不能将子项附加到输入元素。 It is a standalone element. 它是一个独立的元素。 You can however append an input element to a div element. 但是,您可以将输入元素附加到div元素。

No, you cannot append a child to an input, This is because the standard states that this element has the content model as Empty. 不可以,您不能将子项附加到输入中,这是因为标准声明此元素的内容模型为Empty。

it only has properties that can be accessed by the "." 它仅具有可以由“。”访问的属性。 syntax like 语法像

input.propertie

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

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