Sergej Fomin
Sergej Fomin

Reputation: 2002

Jquery Append Existing element

Jquery .append() method: "Insert content, specified by the parameter, TO THE END(!!!) of each element in the set of matched elements." Api

First, adds to the END (ok):

	var tbody = $('tbody');
	var row = $('<tr><td>4</td></tr>');

		tbody.append(row);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
	<tbody>
		
	<tr><td>1</td></tr>
	<tr><td>2</td></tr>
	<tr><td>3</td></tr>

	</tbody>
</table>

Second, replaces everything (doesn't add to the end):

	var tbody = $('tbody');
	var row = tbody.children('tr:first');

		tbody.append(row);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
	<tbody>
		
	<tr><td>1</td></tr>
	<tr><td>2</td></tr>
	<tr><td>3</td></tr>

	</tbody>
</table>

If target.append(element) should add element to the end of target, second example should output 1 2 3 1, and not 2 3 1.

QUESTION: Why does the second example output 2 3 1?

Upvotes: 0

Views: 82

Answers (2)

You should add clone for tr

var tbody = $('tbody');
var row = tbody.children('tr:first').clone();
tbody.append(row);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
	<tbody>
		
	<tr><td>1</td></tr>
	<tr><td>2</td></tr>
	<tr><td>3</td></tr>

	</tbody>
</table>

Upvotes: 1

user3154108
user3154108

Reputation: 1294

appendremoves elements from the dom before appending them. If you want to retain the original element where it is, you need to clone it first, then append the clone.

Upvotes: 1

Related Questions