2

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); 
2
  • 1
    What is the node variable? Commented Jul 12, 2013 at 17:11
  • @Fals <div id"something"></div> Commented Jul 12, 2013 at 17:24

3 Answers 3

2

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); } 
Sign up to request clarification or add additional context in comments.

Comments

2
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); 

Comments

1

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) } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.