Sanmveg saini
Sanmveg saini

Reputation: 750

Adding n <td> to every <tr> in a table

My purpose is simple is to add 'n' <td> to every <tr> in a table.

the problem i am facing is that, it is adding only one <td>, not n <td>, in the last <tr> ,not in all <tr>, with class 'n'

var actions = function(){
	return {          // this is going to return a long object containg a list of mny function which can be called any time 
		whichPattern: "pattern1",
		addSlots:function(n){
			var e =document.getElementById(this.whichPattern),
				c = e.children[0].children,
				ap_e = document.createElement('td');
					for(var i=0; i<c.length; i++){
						for(var j=0; j<=n; j++){
							var parent = c[i];
							ap_e.setAttribute("class", String(j));
							parent.appendChild(ap_e);
						}
					};
			pattern_config[this.whichPattern].WP_slotsCounter=n;
			//console.log(this);
		},
	}
};

var pattern_config = {
	pattern1:{
		WP_slotsCounter:0,
	},
};

window.onload = actions().addSlots(3)
<head>
<script type="text/javascript" src="actions.js" ></script>
</head>
<body>

<div id="pattern_body">
<div></div>
<table id="pattern1" border="2">
<tr class="kick instrument">
  <td class='1'>gg</td>
  <td class="2">dd</td>
</tr>
<tr class="snare instrument">
  <td class='1'>vv</td>
  <td class="2">aa</td>
</tr>
<tr class="cymbal instrument">
  <td class='1'>kk</td>
  <td class="2">tt</td>
</tr>
</table>
</div>
</body>

Upvotes: 0

Views: 97

Answers (1)

user1106925
user1106925

Reputation:

A node can exist only in one location in the tree at a time.

You can use .cloneNode(true) to make a copy to append.

var clone = ap_e.cloneNode(true);
clone.className = String(j);
parent.appendChild(clone);

I also changed setAttribute to set the className property instead.


In this particular case, since the node is really pretty simple, you may just want to create it in the same place where you're appending it instead of creating it beforehand and cloning it.

Upvotes: 1

Related Questions