0

Normally, I write my code like this:

var a = document.createElement('div');
var b = document.createElement('div');
a.appendChild(b);

This works. Now I tried to make it more compact:

var a,b;
a = b = document.createElement('div');
a.appendChild(b);

However, this way JS throws an error:

Failed to execute 'appendChild' on 'Node': The new child element contains the parent.

What is happening here?

1 Answer 1

2

You assume that:

  a = b = document.createElement('div');

is the same as:

 a = document.createElement('div');
 b = document.createElement('div');

It isn't. It is rather the same as:

 b = document.createElement('div');
 a = b;

And therefore a and b are actually the same thing. To copy instead of referencing (if you really need a oneliner):

  a = (b = document.createElement('div')).cloneNode(false);

Or a oneliner for multiple:

  const [a, b, c, d] = Array.from({ length: 4 }, () => document.createElement("div"));
Sign up to request clarification or add additional context in comments.

2 Comments

Actually, I tried to create more than two divs with a oneliner. But this way it gets too complicated.
cloneNode takes exactly one argument.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.