Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to duplicate anything that has a specific classname? 6

Status
Not open for further replies.

Sleidia

Technical User
May 4, 2001
1,284
FR
Hello :)

I know how to get an object and its attributes
but how do I duplicate it dynamically wherever
I want in the document?

Thanks!
 
I can't see writing js without a js library. here is how you clone with jquery
Code:
var copy = $("selector").clone();

Jason Meckley
Programmer
Specialty Bakers, Inc.

faq855-7190
faq732-7259
 
Close:

var newobject = document.getElementbyId('idofobject').cloneNode(true);


Then when you want to place it somewhere else, say inside a div:

document.getElementById('mydiv').appendChild(newobject);


----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.
 
jmeckley said:
I can't see writing js without a js library.

That's the problem with libraries - people learn only how to use them, and can't write 'vanilla' JavaScript code. That does not a good coder make, IMHO.

Dan



Coedit Limited - Delivering standards compliant, accessible web solutions

Dan's Page [blue]@[/blue] Code Couch:
Code Couch Tech Snippets & Info:
 
Dan this is true of any library, in any language. It's the difference between understanding the language vs. understanding the library/framework.

On the flip side there is value to using libraries and frameworks to reduce development time and increase readability.

I would say that if for no other reason, jquery* abstracts the browser variations of javascript and that alone justifies it's use over raw javascript. my scripts can reveal intent without the technical concerns of multi-browser support.

*Any js library really: prototype, moo tools, dojo, etc.

Jason Meckley
Programmer
Specialty Bakers, Inc.

faq855-7190
faq732-7259
 
Hi again,

Vacunita, I've tried this :

Code:
function hd_layer_duplicate ( source , target ) {

var duplicate = document.getElementbyId( source ).cloneNode(true);
var parent_node = document.getElementById( target );
parent_node.appendChild( duplicate );

}

... But I get an error "Error: document.getElementbyId is not a function"

What's wrong?
 
document.getElementById() should do the trick. js is case sensitive.

Jason Meckley
Programmer
Specialty Bakers, Inc.

faq855-7190
faq732-7259
 
Thanks a lot :)

The function duplicates correctly the <tr>.....</tr>
but now I would like to have the cloned part to be inserted right after the source id (placed in tr tag) instead of at the bottom of the table (which the code does).

How could I achieve that?

Code:
function hd_layer_duplicate ( source , target ) {

var source_copy = document.getElementById( source ).cloneNode(true);
var target = document.getElementById( target ).parentNode;

target.appendChild( source_copy );

}

Many thanks again! :)

 
Unfortunately tables are a different beast specially in IE.

You need to create the row, and then the cells individually for it to work in IE.

using insertRow you can specify the position of the inserted row.
object.insertRow(1); would insert a row after the first row of the table.

Then you'd need to create the cells for the row.

You can use the sourceobject.cells.length to get the number of cells to create, and then use a for loop to create them.

Then you can change their innerHTML to match the one of your source row's cells:

Code:
function addmyrow(mysource,mydest){
var tsource=document.getElementById(mysource);
var tdest=document.getElementById(mydest);
\\create new row
var mynewrow=tdest.insertRow(1); 

\\create cells in row
var cell1=mynewrow.insertCell(0);
var cell2=mynewrow.insertCell(1);
var cell3=mynewrow.insertCell(2);

\\create the contents of the cells
cell1.innerHTML=tsource.cells[0].innerHTML;
cell2.innerHTML=tsource.cells[1].innerHTML;
cell3.innerHTML=tsource.cells[2].innerHTML;

}


----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.
 
Thanks Vacunuta but it doesn't seem to be usable with cloneNode which was chosen specifically to avoid creating the added row by hand.

... or am I making a mistake?
 
You'll need to decide what's more important, constructing the row directly by using appendChild, or being able to position it in a specific place in the table; but having to build it cell by cell.

As I said you can use a for loop to dynamically construct the cells so you don't have to it manually.

Code:
[green]\\Get the table you wish to insert the row into[/green]
var mytable=document.getElementById('mytable');

[green]\\Insert Empty Row into table[/green]
var newrow=mytable.insertRow(1);

[green]\\get Row you wish to clone[/green]
var getrow=document.getElementById('mynewrow');

[green]\\Get number of cells to construct[/green]
var mycells=document.getElementById('mynewrow').cells.length-1;

[green]\\start loop to construct cells[/green]
for(var i=0;i<=mycells;i++){
[green]\\Create new cell[/green]
var newcell=newrow.insertCell(i);
[green]\\Copy cell contents to new cell[/green]
newcell.innerHTML=getrow.cells[i].innerHTML;
}



----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.
 
Thanks a lot, I didn't know about this limitation.

Well, I have to use cloneNode instead of creating cells because each cell contains several form elements, some quite complicated.

The beauty of cloneNode is that you simply clone some complex HTML and that's it. Too bad it can't be placed anywhere in the table though :(
 
Perhaps I'm missing something, because this works just fine for me in both IE 8 and Fx 3.0.x:

Code:
<html>
<head>
   <script type="text/javascript">

      var tableBody, rowToClone;

      window.onload = function() {
         tableBody = document.getElementById('myTable').tBodies[0];
         rowToClone = tableBody.rows[0];

         cloneRow('A new row', -1);
         cloneRow('Another new row', -1);
         cloneRow('New row inserted after first row', 1);
      }

      function cloneRow(textForFirstCell, newRowIndex) {
         var newRow = rowToClone.cloneNode(true);
         tableBody.appendChild(newRow);

         // This must be doen AFTER adding the row to the table, otherwise the cells collection is not initialised
         newRow.cells[0].innerHTML = textForFirstCell;

         if (newRowIndex != -1) {
            tableBody.insertBefore(newRow, tableBody.rows[newRowIndex]);
         }
      }

   </script>
</head>

<body>
   <table id="myTable" border="1" cellspacing="0" cellpadding="5">
      <tbody>
         <tr>
            <td>Row 1</td>
            <td><input type="text" value="Text" /></td>
            <td><select><option>Select</option></select></td>
            <td><input type="button" value="Button" /></td>
         </tr>
      </tbody>
   </table>
</body>
</html>

Dan



Coedit Limited - Delivering standards compliant, accessible web solutions

Dan's Page [blue]@[/blue] Code Couch:
Code Couch Tech Snippets & Info:
 

Wow, that's wonderful!

Thanks for sharing this!
 
this is where a library begins to pay off. I'm sure it's possible with prototype. here is the jquery code to clone and insert a row on a button click.
Code:
<html>
	<head>
		<script src="jquery-1.3.2.min.js"></script>
		<script>
			$(function(){
				$(":button").click(function(){
					var copy = $(".copy").clone();
					$(".copy").after(copy);
				});
			});
		</script>
	</head>
	<body>
		<table>
			<tr>
				<td>Row 1</td>
				<td><input type="text" value="Text" /></td>
				<td><select><option>Select</option></select></td>
				<td><input type="button" value="Button" /></td>
			</tr>
			<tr class="copy">
				<td>Row 2</td>
				<td><input type="text" value="Text" /></td>
				<td><select><option>Select</option></select></td>
				<td><input type="button" value="Button" /></td>
			</tr>
			<tr>
				<td>Row 3</td>
				<td><input type="text" value="Text" /></td>
				<td><select><option>Select</option></select></td>
				<td><input type="button" value="Button" /></td>
			</tr>
		</table>
		<input type="button" value="duplicate row 2" />
	</body>
</html>
expressing the intent of what will happen is stated without the details of how it will happen.

Jason Meckley
Programmer
Specialty Bakers, Inc.

faq855-7190
faq732-7259
 
Dan's code ends up begin similar to mine in that at then end he uses the innerHTML to create the cell contents.

I never said you needed to construct the contents of the cells by hand each time.

If you already had all the form elements constructed somewhere else inside the cells you wanted to clone, using the innerHTML would just transfer all that to the newly created cell.

With that said, I could never get the contents of the cloned row to show up like:

var clonedrow=sorucerow.cloneNode(true);
var newrow.cells[0].innerHTML=clonedrow.cells[0].innerHTML.

It never worked in IE for me.

Which is why I sued the other method. Which again doesn't mean you need to build it form scratch each time, it just means it uses the content of the cells from another row of the table to create the new cells content.








----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.
 
I only used innerHTML to set the contents of the first cell just to prove the rows were unique. The cloneNode method did all the work cloning everything.

Dan



Coedit Limited - Delivering standards compliant, accessible web solutions

Dan's Page [blue]@[/blue] Code Couch:
Code Couch Tech Snippets & Info:
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top