sherlock
sherlock

Reputation: 764

How to appendChild without removing whats already there?

I am trying to append four <canvas> elements to a node, appendChild() seems to get rid of what was already there, so i tried to combine them all before appending them... what is the best way to do this, I get DOM exception 8 with what i have below.

// Initialize Canvases
var newCanvas1 = document.createElement('canvas');
newCanvas1.setAttribute('width', 300);
newCanvas1.setAttribute('height', 300);
var newCanvas2 = newCanvas1, newCanvas3 = newCanvas1, newCanvas4 = newCanvas1;
newCanvas1.setAttribute('id', nodeID + 'canvas1');
newCanvas2.setAttribute('id', nodeID + 'canvas2');
newCanvas3.setAttribute('id', nodeID + 'canvas3');
newCanvas4.setAttribute('id', nodeID + 'canvas4');

var canvases = newCanvas1 + newCanvas2 + newCanvas3 + newCanvas4;

console.log(canvases);

node.appendChild(canvases);

Upvotes: 2

Views: 2642

Answers (3)

Ja͢ck
Ja͢ck

Reputation: 173652

New elements can only be created by either using Node.cloneNode() or document.createElement(); anything else just creates another reference to the same object.

You can easily reduce your code duplication by writing a simple loop to create your elements:

for (var i = 1; i <= 4; ++i) {
    var canvas = document.createElement('canvas');
    canvas.width = 300;
    canvas.height = 300;
    canvas.id = nodeID + 'canvas' + i;

    node.appendChild(canvas);
}

Upvotes: 2

sherlock
sherlock

Reputation: 764

Ended up just doing this, which is quite re-usable:

function createElement(parent, element, name, width, height){
    var newNode = document.createElement(element);
    newNode.setAttribute('width', width);
    newNode.setAttribute('height', height);
    newNode.setAttribute('id', nodeID + name);
    parent.appendChild(newNode)
}

Upvotes: 1

Populus
Populus

Reputation: 7680

var newCanvas2 = newCanvas1, newCanvas3 = newCanvas1, newCanvas4 = newCanvas1;

This does not create 4 different canvas objects, all it did was reference newCanvas2, newCanvas3, and newCanvas4 to newCanvas1

You need to create all 4 separately:

var newCanvas1 = document.createElement('canvas'),
    newCanvas2 = document.createElement('canvas'),
    newCanvas3 = document.createElement('canvas'),
    newCanvas4 = document.createElement('canvas');

Then append them separately too:

node.appendChild(newCanvas1);
node.appendChild(newCanvas2);
node.appendChild(newCanvas3);
node.appendChild(newCanvas4);

Upvotes: 2

Related Questions