How to create an element with child without adding it?

0

Imagine:

var pai = document.createElement('div');
var filho = document.createElement('div');

I want the child to be inside the parent before adding it to the document. It is impossible with parent.appendChild (child) because parent is in the document before adding a child, how do I?

PS: I do not want to add parent so add the child and then remove parent saving the new format.

    
asked by anonymous 28.02.2018 / 23:27

2 answers

1
  

It is impossible with parent.appendChild (child) because it is necessary for parent to be in the document before adding a child

This statement is not true.

You can start by checking documentation , and confirm that there is no mention of statement he made.

However, we can by appendChild in code and see that it works by adding the node, even when both are not in the DOM:

var pai = document.createElement('div');
var filho = document.createElement('div');

console.log('Pai tem ${pai.childNodes.length} filhos'); //Pai tem 0 filhos
pai.appendChild(filho);
console.log('Pai tem ${pai.childNodes.length} filhos'); //Pai tem 1 filhos

for (let i = 0; i < pai.childNodes.length; ++i){
  console.log('Filho ${i} é ${pai.childNodes[i].tagName}');
}

Concluding:

It is in fact with the function appendChild that adds children to nodes that are not already in the DOM.

    
01.03.2018 / 01:09
0

Example with innerHTML :

document.getElementById ('exemplo').innerHTML = '<div> 1 <div> 2 </div> </div>'

The exemplo element can be a div , be careful, if you use a container with something inside the contents will be deleted, to add more content without deleting what you already have += instead of =

    
01.03.2018 / 01:20