简体   繁体   中英

Can I call appendChild on any HTML element?

Does anybody know if I can call appendChild on any HTML element ?

Specifically I need to do it on input type='text' and it seems to work ? 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 ?

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 ? but is this correct ?

<input> elements are defined as empty. They still have standard DOM methods on them, but they aren't allowed to have child nodes. 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. You should not do this.

From the w3.org on input element :

Content model: Empty.

It's invalid to put an element inside an input .

If you want to set the value of the input, use the value property :

input.value = 'someText';

If what you want is to add an element before your input, use insertBefore :

input.parentNode.insertBefore(div, input);

To insert the div after your input, you would do

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.

No, you cannot append a child to an input, This is because the standard states that this element has the content model as Empty.

it only has properties that can be accessed by the "." syntax like

input.propertie

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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