How to create an element with child without adding it?

Asked

Viewed 94 times

0

Imagine:

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

I want the son is inside the parent before adding it to the document. It is impossible with parent.appendchild(child) as it is necessary that father is in the document before adding a child, how to proceed?

PS: I don’t want to add parent so add the child and then remove parent by saving the new format.

  • serves innerHTML instead of createElement?

  • @Guilherme Costamilam, innerHTML will do, but I have doubts if it will work

2 answers

1


It is impossible with father.appendchild(son) because it is necessary that father be in the document before adding a child

That statement is not true.

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

However, we can put the 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 indeed with the function appendChild who adds children to us who are not yet in the GIFT.

  • In fact, curious, I executed the function and it had not worked, but now it worked... well, very obligated1

0

Example with innerHTML:

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

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

  • worked! thanks.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.